lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 43e759748eb626c69140dc45d1a4fd72262b570d | 0 | PaulKlinger/Sprog-App | package com.almoturg.sprog.model;
import com.annimon.stream.Stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TimeZone;
public class PoemStatistics {
private List<Poem> poems;
public long num;
public long total_words;
public double avg_words;
public long total_score;
public double avg_score;
public double med_score;
public long total_gold;
public long total_timmy;
public long total_timmy_fucking_died;
public PoemStatistics(List<Poem> poems) {
this.poems = poems;
num = poems.size();
for (Poem p : poems) {
// use StringTokenizer for performance reasons
// String.split is far slower, even with compiled pattern
StringTokenizer st = new StringTokenizer(p.content);
total_words += st.countTokens();
total_score += p.score;
total_gold += p.gold;
if (p.content.toLowerCase().contains("timmy")) {
total_timmy++;
}
if (p.content.toLowerCase().contains("timmy fucking died")) {
total_timmy_fucking_died++;
}
}
avg_words = ((double) total_words) / num;
avg_score = ((double) total_score) / num;
med_score = median(Stream.of(poems).mapToDouble(p -> p.score).toArray());
}
public LinkedHashMap<Integer, Integer> getMonthNPoems() {
Calendar date = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
date.setTimeInMillis(getFirstTimestamp());
Calendar now = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
LinkedHashMap<Integer, Integer> monthNPoems = new LinkedHashMap<>();
do {
monthNPoems.put(totalMonths(date), 0);
date.add(Calendar.MONTH, 1);
} while (date.get(Calendar.YEAR) < now.get(Calendar.YEAR) ||
date.get(Calendar.MONTH) <= now.get(Calendar.MONTH));
int pkey;
for (Poem p : poems) {
date.setTimeInMillis(p.timestamp_long);
pkey = totalMonths(date);
monthNPoems.put(pkey, monthNPoems.get(pkey) + 1);
}
return monthNPoems;
}
public LinkedHashMap<Integer, Double> getMonthAvgScore() {
Calendar date = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
date.setTimeInMillis(getFirstTimestamp());
Calendar now = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
LinkedHashMap<Integer, Double> monthsAvgScore = new LinkedHashMap<>();
HashMap<Integer, List<Poem>> monthsPoems = new HashMap<>();
do {
monthsAvgScore.put(totalMonths(date), 0d);
monthsPoems.put(totalMonths(date), new ArrayList<>());
date.add(Calendar.MONTH, 1);
} while (date.get(Calendar.YEAR) < now.get(Calendar.YEAR) ||
date.get(Calendar.MONTH) <= now.get(Calendar.MONTH));
int pkey;
for (Poem p : poems) {
date.setTimeInMillis(p.timestamp_long);
pkey = totalMonths(date);
monthsPoems.get(pkey).add(p);
}
for (int key : monthsPoems.keySet()) {
monthsAvgScore.put(key, Stream.of(monthsPoems.get(key))
.mapToDouble(p -> p.score).sum() / monthsPoems.get(key).size());
}
return monthsAvgScore;
}
private static int totalMonths(Calendar cal) {
return cal.get(Calendar.YEAR) * 12 + cal.get(Calendar.MONTH);
}
private static double median(double[] m) {
if (m.length == 0) {
return 0;
}
Arrays.sort(m);
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
private long getFirstTimestamp() {
return (long) (Stream.of(poems).mapToDouble(p -> p.timestamp).min().orElse(-1) * 1000);
}
}
| app/src/main/java/com/almoturg/sprog/model/PoemStatistics.java | package com.almoturg.sprog.model;
import com.annimon.stream.Stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.TimeZone;
public class PoemStatistics {
private List<Poem> poems;
public long num;
public long total_words;
public double avg_words;
public long total_score;
public double avg_score;
public double med_score;
public long total_gold;
public long total_timmy;
public long total_timmy_fucking_died;
public PoemStatistics(List<Poem> poems) {
this.poems = poems;
num = poems.size();
for (Poem p : poems) {
total_words += p.content.split("\\s+").length;
total_score += p.score;
total_gold += p.gold;
if (p.content.toLowerCase().contains("timmy")) {
total_timmy++;
}
if (p.content.toLowerCase().contains("timmy fucking died")) {
total_timmy_fucking_died++;
}
}
avg_words = ((double) total_words) / num;
avg_score = ((double) total_score) / num;
med_score = median(Stream.of(poems).mapToDouble(p -> p.score).toArray());
}
public LinkedHashMap<Integer, Integer> getMonthNPoems() {
Calendar date = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
date.setTimeInMillis(getFirstTimestamp());
Calendar now = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
LinkedHashMap<Integer, Integer> monthNPoems = new LinkedHashMap<>();
do {
monthNPoems.put(totalMonths(date), 0);
date.add(Calendar.MONTH, 1);
} while (date.get(Calendar.YEAR) < now.get(Calendar.YEAR) ||
date.get(Calendar.MONTH) <= now.get(Calendar.MONTH));
int pkey;
for (Poem p : poems) {
date.setTimeInMillis(p.timestamp_long);
pkey = totalMonths(date);
monthNPoems.put(pkey, monthNPoems.get(pkey) + 1);
}
return monthNPoems;
}
public LinkedHashMap<Integer, Double> getMonthAvgScore() {
Calendar date = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
date.setTimeInMillis(getFirstTimestamp());
Calendar now = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
LinkedHashMap<Integer, Double> monthsAvgScore = new LinkedHashMap<>();
HashMap<Integer, List<Poem>> monthsPoems = new HashMap<>();
do {
monthsAvgScore.put(totalMonths(date), 0d);
monthsPoems.put(totalMonths(date), new ArrayList<>());
date.add(Calendar.MONTH, 1);
} while (date.get(Calendar.YEAR) < now.get(Calendar.YEAR) ||
date.get(Calendar.MONTH) <= now.get(Calendar.MONTH));
int pkey;
for (Poem p : poems) {
date.setTimeInMillis(p.timestamp_long);
pkey = totalMonths(date);
monthsPoems.get(pkey).add(p);
}
for (int key : monthsPoems.keySet()) {
monthsAvgScore.put(key, Stream.of(monthsPoems.get(key))
.mapToDouble(p -> p.score).sum() / monthsPoems.get(key).size());
}
return monthsAvgScore;
}
private static int totalMonths(Calendar cal) {
return cal.get(Calendar.YEAR) * 12 + cal.get(Calendar.MONTH);
}
private static double median(double[] m) {
if (m.length == 0) {
return 0;
}
Arrays.sort(m);
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
private long getFirstTimestamp() {
return (long) (Stream.of(poems).mapToDouble(p -> p.timestamp).min().orElse(-1) * 1000);
}
}
| use StringTokenizer instead of String.split to count words
This makes a huge difference in performance. I also tried split with a compiled regex but that didn't help at all.
| app/src/main/java/com/almoturg/sprog/model/PoemStatistics.java | use StringTokenizer instead of String.split to count words | <ide><path>pp/src/main/java/com/almoturg/sprog/model/PoemStatistics.java
<ide> import java.util.HashMap;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<add>import java.util.StringTokenizer;
<ide> import java.util.TimeZone;
<ide>
<ide> public class PoemStatistics {
<ide> num = poems.size();
<ide>
<ide> for (Poem p : poems) {
<del> total_words += p.content.split("\\s+").length;
<add> // use StringTokenizer for performance reasons
<add> // String.split is far slower, even with compiled pattern
<add> StringTokenizer st = new StringTokenizer(p.content);
<add> total_words += st.countTokens();
<ide> total_score += p.score;
<ide> total_gold += p.gold;
<ide> if (p.content.toLowerCase().contains("timmy")) { |
|
Java | mit | 8fc9eaa50a3bb8cf569ec3cef6e31b8c247ebf06 | 0 | gabelew/SimCity201 | package city.gui;
import restaurant.Restaurant;
import javax.swing.*;
import bank.BankBuilding;
import atHome.city.Apartment;
import atHome.city.Home;
import atHome.city.Residence;
import city.MarketAgent;
import city.PersonAgent;
import city.roles.BankCustomerRole;
import city.roles.Role;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.regex.Pattern;
/**
* Panel in frame that contains all the restaurant information,
* including host, cook, waiters, and customers.
*/
public class InfoPanel extends JPanel implements KeyListener {
private static final long serialVersionUID = 1L;
private static final int REST_PANEL_GAP = 20;
private static final int GROUP_PANEL_GAP = 10;
private static final int GROUP_NROWS = 1;
private static final int GROUP_NCOLUMNS = 1;
private static final int NCOLUMNS = 1;
private static final int NROWS = 2;
private static final double PERSONS_DEFAULT_CASH = 200.00;
private static final double NO_CASH = 0.0;
private ListPanel personPanel = new ListPanel(this, "Persons");
private JPanel group = new JPanel();
private SimCityGui gui; //reference to main gui
public InfoPanel(SimCityGui gui) {
//markets.add(new MarketAgent("Vons Market"));
//markets.add(new MarketAgent("Sprouts Market"));
//markets.add(new MarketAgent("CostCo"));
this.gui = gui;
setLayout(new GridLayout(NROWS, NCOLUMNS, REST_PANEL_GAP, REST_PANEL_GAP));
group.setLayout(new GridLayout(GROUP_NROWS, GROUP_NCOLUMNS, GROUP_PANEL_GAP, GROUP_PANEL_GAP));
add(personPanel);
personPanel.getTypeNameHere().addKeyListener(this);
}
public void setHungry(String type, String name) {
if (type.equals("Persons")) {
for (PersonAgent temp: gui.persons){
if (temp.getName() == name){}
//temp.getGui().setHungry();
}
}
}
/* public void setWorking(String type, String name) {
if (type.equals("Waiters")) {
for (WaiterAgent temp: waiters) {
if (temp.getName() == name)
{
temp.getGui().setWorking();
}
}
}
}
public void askBreak(String name) {
for (WaiterAgent temp: waiters) {
if (temp.getName() == name)
temp.getGui().askBreak();
}
}*/
/**
* Adds a customer or waiter to the appropriate list
*
* @param type indicates whether the person is a customer or waiter (later)
* @param name name of person
*/
private Residence findOpenHome(String name){
if(gui.apartmentsAvaiable() && !(name.toLowerCase().contains("home")) ){
for(Apartment a: gui.apartments){
if(a.noVacancies == false){
/*p.setHome(a);
a.addRenter(p);
break;*/
return a;
}
}
}else if(gui.persons.size() <= 160){
for(Home h : gui.getHomes())
{
if(h.owner == null){
/*
p.setHome(h);
h.owner = p;
break;*/
return h;
}
}
for(Apartment a: gui.apartments){
if(a.noVacancies == false){
/*p.setHome(a);
a.addRenter(p);
break;*/
return a;
}
}
}
return null;
}
public void addPerson(String type, String name) {
if (type.equals("Persons")) {
PersonAgent p = null;
Residence residence = findOpenHome(name);
if(stringIsDouble(name)){
p = new PersonAgent(name, Double.valueOf(name),gui, residence);
}else if(name.toLowerCase().contains("rami") || name.toLowerCase().contains("mahdi")
|| name.toLowerCase().contains("ditch") || name.toLowerCase().contains("broke")){
p = new PersonAgent(name, NO_CASH,gui, residence);
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 0, "personal");
}else if(name.toLowerCase().contains("poor")){
p = new PersonAgent(name, 50,gui, residence);
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 200, "personal");
}else{
p = new PersonAgent(name, PERSONS_DEFAULT_CASH, gui, residence);
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 500, "personal");
}
if(residence instanceof Apartment){
((Apartment)residence).addRenter(p);
}else{
((Home)residence).owner = p;
}
p.addAtHomeRole();
if(name.toLowerCase().contains("waiter") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}
}
else if(name.toLowerCase().contains("waiter") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("host") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
System.out.println("already has host");
hasHost = true;
}
}
}
if(!hasHost){
System.out.println("making host");
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}
}else if(name.toLowerCase().contains("host") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}
}else if(name.toLowerCase().contains("cook") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}
}else if(name.toLowerCase().contains("cook") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}
}else if(name.toLowerCase().contains("cashier") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}
}else if(name.toLowerCase().contains("cashier") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}
}else if(name.toLowerCase().contains("clerk") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
MarketAgent m = gui.markets.get(0);
boolean hasMarket = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasMarket = true;
}
}
}
if(!hasMarket){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("02")){
MarketAgent m = gui.markets.get(1);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("03")){
MarketAgent m = gui.markets.get(2);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("04")){
MarketAgent m = gui.markets.get(3);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("05")){
MarketAgent m = gui.markets.get(4);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}
}else if(name.toLowerCase().contains("clerk") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
MarketAgent m = gui.markets.get(0);
boolean hasMarket = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasMarket = true;
}
}
}
if(!hasMarket){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("02")){
MarketAgent m = gui.markets.get(1);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("03")){
MarketAgent m = gui.markets.get(2);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("04")){
MarketAgent m = gui.markets.get(3);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("05")){
MarketAgent m = gui.markets.get(4);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}
}else if(name.toLowerCase().contains("deliveryman") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
MarketAgent m = gui.markets.get(0);
boolean hasMarket = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasMarket = true;
}
}
}
if(!hasMarket){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("02")){
MarketAgent m = gui.markets.get(1);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("03")){
MarketAgent m = gui.markets.get(2);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("04")){
MarketAgent m = gui.markets.get(3);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("05")){
MarketAgent m = gui.markets.get(4);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}
}else if(name.toLowerCase().contains("deliveryman") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
MarketAgent m = gui.markets.get(0);
boolean hasMarket = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasMarket = true;
}
}
}
if(!hasMarket){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("02")){
MarketAgent m = gui.markets.get(1);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("03")){
MarketAgent m = gui.markets.get(2);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("04")){
MarketAgent m = gui.markets.get(3);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("05")){
MarketAgent m = gui.markets.get(4);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}
} else if(name.toLowerCase().contains("rmanager")) {
if(name.toLowerCase().contains("01")) {
Restaurant r = gui.restaurants.get(0);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
} else if(name.toLowerCase().contains("02")) {
Restaurant r = gui.restaurants.get(1);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
} else if(name.toLowerCase().contains("03")) {
Restaurant r = gui.restaurants.get(2);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
} else if(name.toLowerCase().contains("04")) {
Restaurant r = gui.restaurants.get(3);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
} else if(name.toLowerCase().contains("05")) {
Restaurant r = gui.restaurants.get(4);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
}
}
PersonGui g = new PersonGui(p, gui);
g.setPresent(true);
gui.animationPanel.addGui(g);// dw
for(Restaurant r: gui.getRestaurants()){
p.addRestaurant(r);
}
for(MarketAgent m: gui.getMarkets()){
p.addMarket(m);
}
for(BankBuilding b: gui.getBanks()){
p.addBank(b);
}
p.setGui(g);
gui.persons.add(p);
p.startThread();
}
}
/* public void setCustomerEnabled(CustomerAgent c){
personPanel.setCustomerEnabled(c.getName());
}
public void setTableEnabled(int tableNumber){
tablesPanel.setTableEnabled(tableNumber);
}
public void setTableDisabled(int tableNumber){
tablesPanel.setTableDisabled(tableNumber);
}*/
public void pauseAgents()
{
/*if(tablesPanel.getPauseButtonLabel() == "Pause")
{
for (CustomerAgent temp: customers)
{
temp.pauseAgent();
}
for (WaiterAgent temp: waiters)
{
temp.pauseAgent();
}
for (MarketAgent temp: markets)
{
temp.pauseAgent();
}
//host.pauseAgent();
//cook.pauseAgent();
//cashier.pauseAgent();
}
else
{
for(CustomerAgent temp: customers)
{
temp.resumeAgent();
}
for (WaiterAgent temp: waiters)
{
temp.resumeAgent();
}
for (MarketAgent temp: markets)
{
temp.resumeAgent();
}
// host.resumeAgent();
// cook.resumeAgent();
//cashier.resumeAgent();
}
tablesPanel.changePauseButton();
*/}
public void setWaiterOnBreak(String name) {
//waitersPanel.setWaiterOnBreak(name);
}
public void setWaiterCantBreak(String name) {
//waitersPanel.setWaiterCantBreak(name);
}
public void setWaiterBreakable(String name) {
//waitersPanel.setWaiterBreakable(name);
}
public void setWaiterUnbreakable(String name) {
//waitersPanel.setWaiterUnbreakable(name);
}
public boolean stringIsDouble(String myString){
final String Digits = "(\\p{Digit}+)";
final String HexDigits = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally
// signed decimal integer.
final String Exp = "[eE][+-]?"+Digits;
final String fpRegex =
("[\\x00-\\x20]*"+ // Optional leading "whitespace"
"[+-]?(" + // Optional sign character
"NaN|" + // "NaN" string
"Infinity|" + // "Infinity" string
// A decimal floating-point string representing a finite positive
// number without a leading sign has at most five basic pieces:
// Digits . Digits ExponentPart FloatTypeSuffix
//
// Since this method allows integer-only strings as input
// in addition to strings of floating-point literals, the
// two sub-patterns below are simplifications of the grammar
// productions from the Java Language Specification, 2nd
// edition, section 3.10.2.
// Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
"((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
// . Digits ExponentPart_opt FloatTypeSuffix_opt
"(\\.("+Digits+")("+Exp+")?)|"+
// Hexadecimal strings
"((" +
// 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "(\\.)?)|" +
// 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
")[pP][+-]?" + Digits + "))" +
"[fFdD]?))" +
"[\\x00-\\x20]*");// Optional trailing "whitespace"
if (Pattern.matches(fpRegex, myString))
return true;//Double.valueOf(myString); // Will not throw NumberFormatException
else {
return false;
}
}
@Override
public void keyPressed(KeyEvent e) {
/*if ((e.getKeyCode() == KeyEvent.VK_S) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
cook.badSteaks();
}
if ((e.getKeyCode() == KeyEvent.VK_2) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
cook.cookieMonster();
}
if ((e.getKeyCode() == KeyEvent.VK_D) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
markets.get(0).msgTossEverythingButCookies();
}
if ((e.getKeyCode() == KeyEvent.VK_F) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
cook.setSteaksAmount(5);
}
if ((e.getKeyCode() == KeyEvent.VK_W) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
for(MarketAgent m: markets){
System.out.println("\nMarket Inventory: " + m.getName());
for(MarketAgent.MyFood f: m.foods){
String mstate = null;
for(CookAgent.MyMarket mm: cook.markets){
if(mm.getMarket() == m)
{
mstate = mm.foodInventoryMap.get(f.getChoice()).toString();
}
}
System.out.print("\t" + f.getChoice() + " " + f.getAmount() + " "+ mstate + "\t");
}
System.out.println(" ");
}
}
if ((e.getKeyCode() == KeyEvent.VK_E) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("Cook Inventory: ");
for(CookAgent.Food f: cook.foods){
System.out.print("\t" + f.getChoice() + "\t" + f.getAmount() + "\t");
}
System.out.println(" ");
}
*/
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
public ListPanel getPersonPanel(){
return personPanel;
}
}
| src/city/gui/InfoPanel.java | package city.gui;
import restaurant.Restaurant;
import javax.swing.*;
import bank.BankBuilding;
import atHome.city.Apartment;
import atHome.city.Home;
import atHome.city.Residence;
import city.MarketAgent;
import city.PersonAgent;
import city.roles.BankCustomerRole;
import city.roles.Role;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.regex.Pattern;
/**
* Panel in frame that contains all the restaurant information,
* including host, cook, waiters, and customers.
*/
public class InfoPanel extends JPanel implements KeyListener {
private static final long serialVersionUID = 1L;
private static final int REST_PANEL_GAP = 20;
private static final int GROUP_PANEL_GAP = 10;
private static final int GROUP_NROWS = 1;
private static final int GROUP_NCOLUMNS = 1;
private static final int NCOLUMNS = 1;
private static final int NROWS = 2;
private static final double PERSONS_DEFAULT_CASH = 200.00;
private static final double NO_CASH = 0.0;
private ListPanel personPanel = new ListPanel(this, "Persons");
private JPanel group = new JPanel();
private SimCityGui gui; //reference to main gui
public InfoPanel(SimCityGui gui) {
//markets.add(new MarketAgent("Vons Market"));
//markets.add(new MarketAgent("Sprouts Market"));
//markets.add(new MarketAgent("CostCo"));
this.gui = gui;
setLayout(new GridLayout(NROWS, NCOLUMNS, REST_PANEL_GAP, REST_PANEL_GAP));
group.setLayout(new GridLayout(GROUP_NROWS, GROUP_NCOLUMNS, GROUP_PANEL_GAP, GROUP_PANEL_GAP));
add(personPanel);
personPanel.getTypeNameHere().addKeyListener(this);
}
public void setHungry(String type, String name) {
if (type.equals("Persons")) {
for (PersonAgent temp: gui.persons){
if (temp.getName() == name){}
//temp.getGui().setHungry();
}
}
}
/* public void setWorking(String type, String name) {
if (type.equals("Waiters")) {
for (WaiterAgent temp: waiters) {
if (temp.getName() == name)
{
temp.getGui().setWorking();
}
}
}
}
public void askBreak(String name) {
for (WaiterAgent temp: waiters) {
if (temp.getName() == name)
temp.getGui().askBreak();
}
}*/
/**
* Adds a customer or waiter to the appropriate list
*
* @param type indicates whether the person is a customer or waiter (later)
* @param name name of person
*/
private Residence findOpenHome(String name){
if(gui.apartmentsAvaiable() && !(name.toLowerCase().contains("home")) ){
for(Apartment a: gui.apartments){
if(a.noVacancies == false){
/*p.setHome(a);
a.addRenter(p);
break;*/
return a;
}
}
}else if(gui.persons.size() <= 160){
for(Home h : gui.getHomes())
{
if(h.owner == null){
/*
p.setHome(h);
h.owner = p;
break;*/
return h;
}
}
for(Apartment a: gui.apartments){
if(a.noVacancies == false){
/*p.setHome(a);
a.addRenter(p);
break;*/
return a;
}
}
}
return null;
}
public void addPerson(String type, String name) {
if (type.equals("Persons")) {
PersonAgent p = null;
Residence residence = findOpenHome(name);
if(stringIsDouble(name)){
p = new PersonAgent(name, Double.valueOf(name),gui, residence);
}else if(name.toLowerCase().contains("rami") || name.toLowerCase().contains("mahdi")
|| name.toLowerCase().contains("ditch") || name.toLowerCase().contains("broke")){
p = new PersonAgent(name, NO_CASH,gui, residence);
}else if(name.toLowerCase().contains("poor")){
p = new PersonAgent(name, 50,gui, residence);
}else{
p = new PersonAgent(name, PERSONS_DEFAULT_CASH, gui, residence);
}
if(residence instanceof Apartment){
((Apartment)residence).addRenter(p);
}else{
((Home)residence).owner = p;
}
p.addAtHomeRole();
if(name.toLowerCase().contains("waiter") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.day);
}
}
else if(name.toLowerCase().contains("waiter") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
p.job = p.new MyJob(r.location , "waiter", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("host") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
System.out.println("already has host");
hasHost = true;
}
}
}
if(!hasHost){
System.out.println("making host");
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.day);
}
}
}else if(name.toLowerCase().contains("host") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasHost = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("host")){
hasHost = true;
}
}
}
if(!hasHost){
p.job = p.new MyJob(r.location , "host", PersonAgent.Shift.night);
}
}
}else if(name.toLowerCase().contains("cook") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.day);
}
}
}else if(name.toLowerCase().contains("cook") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasCook = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cook")){
hasCook = true;
}
}
}
if(!hasCook){
p.job = p.new MyJob(r.location , "cook", PersonAgent.Shift.night);
}
}
}else if(name.toLowerCase().contains("cashier") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.day);
p.businessAccount = r.getRestaurantAccount();
}
}
}else if(name.toLowerCase().contains("cashier") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
Restaurant r = gui.restaurants.get(0);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("02")){
Restaurant r = gui.restaurants.get(1);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("03")){
Restaurant r = gui.restaurants.get(2);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("04")){
Restaurant r = gui.restaurants.get(3);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}else if(name.toLowerCase().contains("05")){
Restaurant r = gui.restaurants.get(4);
boolean hasCashier = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("cashier")){
hasCashier = true;
}
}
}
if(!hasCashier){
p.job = p.new MyJob(r.location , "cashier", PersonAgent.Shift.night);
p.businessAccount = r.getRestaurantAccount();
}
}
}else if(name.toLowerCase().contains("clerk") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
MarketAgent m = gui.markets.get(0);
boolean hasMarket = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasMarket = true;
}
}
}
if(!hasMarket){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("02")){
MarketAgent m = gui.markets.get(1);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("03")){
MarketAgent m = gui.markets.get(2);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("04")){
MarketAgent m = gui.markets.get(3);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("05")){
MarketAgent m = gui.markets.get(4);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.day);
}
}
}else if(name.toLowerCase().contains("clerk") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
MarketAgent m = gui.markets.get(0);
boolean hasMarket = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasMarket = true;
}
}
}
if(!hasMarket){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("02")){
MarketAgent m = gui.markets.get(1);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("03")){
MarketAgent m = gui.markets.get(2);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("04")){
MarketAgent m = gui.markets.get(3);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("05")){
MarketAgent m = gui.markets.get(4);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasClerk = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("clerk")){
hasClerk = true;
}
}
}
if(!hasClerk){
p.job = p.new MyJob(m.location , "clerk", PersonAgent.Shift.night);
}
}
}else if(name.toLowerCase().contains("deliveryman") && name.toLowerCase().contains("day")){
if(name.toLowerCase().contains("01")){
MarketAgent m = gui.markets.get(0);
boolean hasMarket = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasMarket = true;
}
}
}
if(!hasMarket){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("02")){
MarketAgent m = gui.markets.get(1);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("03")){
MarketAgent m = gui.markets.get(2);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("04")){
MarketAgent m = gui.markets.get(3);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("05")){
MarketAgent m = gui.markets.get(4);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.day && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.day);
}
}
}else if(name.toLowerCase().contains("deliveryman") && name.toLowerCase().contains("night")){
if(name.toLowerCase().contains("01")){
MarketAgent m = gui.markets.get(0);
boolean hasMarket = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasMarket = true;
}
}
}
if(!hasMarket){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("02")){
MarketAgent m = gui.markets.get(1);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("03")){
MarketAgent m = gui.markets.get(2);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("04")){
MarketAgent m = gui.markets.get(3);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("05")){
MarketAgent m = gui.markets.get(4);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}else if(name.toLowerCase().contains("06")){
MarketAgent m = gui.markets.get(5);
boolean hasdeliveryMan = false;
for(PersonAgent currentP: gui.persons){
if(currentP.job!=null){
if(currentP.job.location == m.location && currentP.job.shift == PersonAgent.Shift.night && currentP.job.type.equalsIgnoreCase("deliveryman")){
hasdeliveryMan = true;
}
}
}
if(!hasdeliveryMan){
p.job = p.new MyJob(m.location , "deliveryman", PersonAgent.Shift.night);
}
}
} else if(name.toLowerCase().contains("rmanager")) {
if(name.toLowerCase().contains("01")) {
Restaurant r = gui.restaurants.get(0);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
} else if(name.toLowerCase().contains("02")) {
Restaurant r = gui.restaurants.get(1);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
} else if(name.toLowerCase().contains("03")) {
Restaurant r = gui.restaurants.get(2);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
} else if(name.toLowerCase().contains("04")) {
Restaurant r = gui.restaurants.get(3);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
} else if(name.toLowerCase().contains("05")) {
Restaurant r = gui.restaurants.get(4);
boolean hasManager = false;
for(PersonAgent currentP: gui.persons) {
if(currentP.job!=null){
if(currentP.job.location == r.location && currentP.job.type.equalsIgnoreCase("manager")){
hasManager = true;
}
}
}
if(!hasManager) {
p.job = p.new MyJob(r.location, "manager", PersonAgent.Shift.none);
p.isManager = true;
BankCustomerRole bcr = null;
for(Role role : p.roles) {
if(role instanceof BankCustomerRole)
bcr = (BankCustomerRole)role;
}
gui.bankAgent.msgOpenAccount(bcr, 2000, "business");
r.setRestaurantAccount(p.businessAccount);
}
}
}
PersonGui g = new PersonGui(p, gui);
g.setPresent(true);
gui.animationPanel.addGui(g);// dw
for(Restaurant r: gui.getRestaurants()){
p.addRestaurant(r);
}
for(MarketAgent m: gui.getMarkets()){
p.addMarket(m);
}
for(BankBuilding b: gui.getBanks()){
p.addBank(b);
}
p.setGui(g);
gui.persons.add(p);
p.startThread();
}
}
/* public void setCustomerEnabled(CustomerAgent c){
personPanel.setCustomerEnabled(c.getName());
}
public void setTableEnabled(int tableNumber){
tablesPanel.setTableEnabled(tableNumber);
}
public void setTableDisabled(int tableNumber){
tablesPanel.setTableDisabled(tableNumber);
}*/
public void pauseAgents()
{
/*if(tablesPanel.getPauseButtonLabel() == "Pause")
{
for (CustomerAgent temp: customers)
{
temp.pauseAgent();
}
for (WaiterAgent temp: waiters)
{
temp.pauseAgent();
}
for (MarketAgent temp: markets)
{
temp.pauseAgent();
}
//host.pauseAgent();
//cook.pauseAgent();
//cashier.pauseAgent();
}
else
{
for(CustomerAgent temp: customers)
{
temp.resumeAgent();
}
for (WaiterAgent temp: waiters)
{
temp.resumeAgent();
}
for (MarketAgent temp: markets)
{
temp.resumeAgent();
}
// host.resumeAgent();
// cook.resumeAgent();
//cashier.resumeAgent();
}
tablesPanel.changePauseButton();
*/}
public void setWaiterOnBreak(String name) {
//waitersPanel.setWaiterOnBreak(name);
}
public void setWaiterCantBreak(String name) {
//waitersPanel.setWaiterCantBreak(name);
}
public void setWaiterBreakable(String name) {
//waitersPanel.setWaiterBreakable(name);
}
public void setWaiterUnbreakable(String name) {
//waitersPanel.setWaiterUnbreakable(name);
}
public boolean stringIsDouble(String myString){
final String Digits = "(\\p{Digit}+)";
final String HexDigits = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally
// signed decimal integer.
final String Exp = "[eE][+-]?"+Digits;
final String fpRegex =
("[\\x00-\\x20]*"+ // Optional leading "whitespace"
"[+-]?(" + // Optional sign character
"NaN|" + // "NaN" string
"Infinity|" + // "Infinity" string
// A decimal floating-point string representing a finite positive
// number without a leading sign has at most five basic pieces:
// Digits . Digits ExponentPart FloatTypeSuffix
//
// Since this method allows integer-only strings as input
// in addition to strings of floating-point literals, the
// two sub-patterns below are simplifications of the grammar
// productions from the Java Language Specification, 2nd
// edition, section 3.10.2.
// Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
"((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
// . Digits ExponentPart_opt FloatTypeSuffix_opt
"(\\.("+Digits+")("+Exp+")?)|"+
// Hexadecimal strings
"((" +
// 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "(\\.)?)|" +
// 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
")[pP][+-]?" + Digits + "))" +
"[fFdD]?))" +
"[\\x00-\\x20]*");// Optional trailing "whitespace"
if (Pattern.matches(fpRegex, myString))
return true;//Double.valueOf(myString); // Will not throw NumberFormatException
else {
return false;
}
}
@Override
public void keyPressed(KeyEvent e) {
/*if ((e.getKeyCode() == KeyEvent.VK_S) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
cook.badSteaks();
}
if ((e.getKeyCode() == KeyEvent.VK_2) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
cook.cookieMonster();
}
if ((e.getKeyCode() == KeyEvent.VK_D) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
markets.get(0).msgTossEverythingButCookies();
}
if ((e.getKeyCode() == KeyEvent.VK_F) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
cook.setSteaksAmount(5);
}
if ((e.getKeyCode() == KeyEvent.VK_W) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
for(MarketAgent m: markets){
System.out.println("\nMarket Inventory: " + m.getName());
for(MarketAgent.MyFood f: m.foods){
String mstate = null;
for(CookAgent.MyMarket mm: cook.markets){
if(mm.getMarket() == m)
{
mstate = mm.foodInventoryMap.get(f.getChoice()).toString();
}
}
System.out.print("\t" + f.getChoice() + " " + f.getAmount() + " "+ mstate + "\t");
}
System.out.println(" ");
}
}
if ((e.getKeyCode() == KeyEvent.VK_E) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("Cook Inventory: ");
for(CookAgent.Food f: cook.foods){
System.out.print("\t" + f.getChoice() + "\t" + f.getAmount() + "\t");
}
System.out.println(" ");
}
*/
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
public ListPanel getPersonPanel(){
return personPanel;
}
}
| Added personal bank accounts for most people.
| src/city/gui/InfoPanel.java | Added personal bank accounts for most people. | <ide><path>rc/city/gui/InfoPanel.java
<ide> p = new PersonAgent(name, Double.valueOf(name),gui, residence);
<ide> }else if(name.toLowerCase().contains("rami") || name.toLowerCase().contains("mahdi")
<ide> || name.toLowerCase().contains("ditch") || name.toLowerCase().contains("broke")){
<del> p = new PersonAgent(name, NO_CASH,gui, residence);
<add> p = new PersonAgent(name, NO_CASH,gui, residence);
<add> BankCustomerRole bcr = null;
<add> for(Role role : p.roles) {
<add> if(role instanceof BankCustomerRole)
<add> bcr = (BankCustomerRole)role;
<add> }
<add> gui.bankAgent.msgOpenAccount(bcr, 0, "personal");
<ide> }else if(name.toLowerCase().contains("poor")){
<del> p = new PersonAgent(name, 50,gui, residence);
<add> p = new PersonAgent(name, 50,gui, residence);
<add> BankCustomerRole bcr = null;
<add> for(Role role : p.roles) {
<add> if(role instanceof BankCustomerRole)
<add> bcr = (BankCustomerRole)role;
<add> }
<add> gui.bankAgent.msgOpenAccount(bcr, 200, "personal");
<ide> }else{
<ide> p = new PersonAgent(name, PERSONS_DEFAULT_CASH, gui, residence);
<add> BankCustomerRole bcr = null;
<add> for(Role role : p.roles) {
<add> if(role instanceof BankCustomerRole)
<add> bcr = (BankCustomerRole)role;
<add> }
<add> gui.bankAgent.msgOpenAccount(bcr, 500, "personal");
<ide> }
<add>
<ide>
<ide> if(residence instanceof Apartment){
<ide> ((Apartment)residence).addRenter(p); |
|
Java | apache-2.0 | d951f3c8948890698485e091be0dca4c56a09f39 | 0 | NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.util.bin.format.pdb;
import java.io.*;
import java.util.*;
import org.xml.sax.SAXException;
import docking.widgets.OptionDialog;
import ghidra.app.cmd.label.SetLabelPrimaryCmd;
import ghidra.app.plugin.core.datamgr.util.DataTypeArchiveUtility;
import ghidra.app.services.DataTypeManagerService;
import ghidra.app.util.NamespaceUtils;
import ghidra.app.util.SymbolPath;
import ghidra.app.util.importer.LibrarySearchPathManager;
import ghidra.app.util.importer.MessageLog;
import ghidra.framework.*;
import ghidra.framework.options.Options;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.mem.DumbMemBufferImpl;
import ghidra.program.model.symbol.*;
import ghidra.util.Msg;
import ghidra.util.SystemUtilities;
import ghidra.util.exception.*;
import ghidra.util.task.TaskMonitor;
import ghidra.util.xml.XmlUtilities;
import ghidra.xml.*;
/**
* Contains methods for finding .pdb files and parsing them.
*/
public class PdbParser {
private static final String PDB_EXE = "pdb.exe";
private static final String README_FILENAME =
Application.getInstallationDirectory() + "\\docs\\README_PDB.html";
public final static File SPECIAL_PDB_LOCATION = new File("C:/WINDOWS/Symbols");
public final static String PDB_STORAGE_PROPERTY = "PDB Storage Directory";
static final String STRUCTURE_KIND = "Structure";
static final String UNION_KIND = "Union";
public final static boolean onWindows =
(Platform.CURRENT_PLATFORM.getOperatingSystem() == OperatingSystem.WINDOWS);
public enum PdbFileType {
PDB, XML;
@Override
public String toString() {
return "." + name().toLowerCase();
}
}
private TaskMonitor monitor;
private final boolean forceAnalysis;
private final File pdbFile;
private final boolean isXML;
private final Program program;
private DataTypeManager dataMgr;
private final DataTypeManagerService service;
private final PdbProgramAttributes programAttributes;
private Process process;
private XmlPullParser parser;
private PdbErrorHandler errHandler;
private PdbErrorReaderThread thread;
private boolean parsed = false;
private CategoryPath pdbCategory;
/**
* Note that the current implementation relies on having all types which are defined
* by the PDB to be available within the dataTypeCache using namespace-based type
* names.
*/
private PdbDataTypeParser dataTypeParser;
private Map<SymbolPath, Boolean> namespaceMap = new TreeMap<>(); // false: simple namespace, true: class namespace
public PdbParser(File pdbFile, Program program, DataTypeManagerService service,
boolean forceAnalysis, TaskMonitor monitor) {
this(pdbFile, program, service, getPdbAttributes(program), forceAnalysis, monitor);
}
public PdbParser(File pdbFile, Program program, DataTypeManagerService service,
PdbProgramAttributes programAttributes, boolean forceAnalysis, TaskMonitor monitor) {
this.pdbFile = pdbFile;
this.pdbCategory = new CategoryPath(CategoryPath.ROOT, pdbFile.getName());
this.program = program;
this.dataMgr = program.getDataTypeManager();
this.service = service;
this.forceAnalysis = forceAnalysis;
this.monitor = monitor != null ? monitor : TaskMonitor.DUMMY;
this.isXML = pdbFile.getAbsolutePath().endsWith(PdbFileType.XML.toString());
this.programAttributes = programAttributes;
}
/**
* Get the program's data type manager
* @return data type manager
*/
DataTypeManager getProgramDataTypeManager() {
return dataMgr;
}
/**
* Get the program associated with this parser
* @return program
*/
Program getProgram() {
return program;
}
/**
* Parse the PDB file, enforcing pre-conditions and post-conditions.
*
* @throws IOException If an I/O error occurs
* @throws PdbException if there was a problem during processing
*/
public void parse() throws IOException, PdbException {
checkPdbLoaded();
checkFileType();
checkOSCompatibility();
if (!forceAnalysis && !programAttributes.isProgramAnalyzed()) {
throw new PdbException("Before loading a PDB, you must first analyze the program.");
}
processPdbContents(false);
// The below code only applies when we are processing .pdb (not .pdb.xml) files
if (!isXML) {
try {//give thread sometime to spin up...
Thread.sleep(1000);
}
catch (Exception e) {
// don't care
}
if (hasErrors()) {
throw new PdbException(getErrorAndWarningMessages());
}
if (hasWarnings()) {
if (SystemUtilities.isInHeadlessMode()) {
throw new PdbException(
getErrorAndWarningMessages() + ".. Skipping PDB processing.");
}
int option = OptionDialog.showYesNoDialog(null, "Continue Loading PDB?",
getErrorAndWarningMessages() + "\n " + "\nContinue anyway?" + "\n " +
"\nPlease note: Invalid disassembly may be produced!");
if (option == OptionDialog.OPTION_ONE) {
cleanup();
processPdbContents(true);//attempt without validation...
}
else {
throw new PdbException(getErrorAndWarningMessages());
}
}
}
else { // only for .pdb.xml files.
verifyPdbSignature();
}
parsed = true;
}
private void checkFileType() throws PdbException {
String pdbFilename = pdbFile.getName();
if (!pdbFilename.endsWith(PdbFileType.PDB.toString()) &&
!pdbFilename.endsWith(PdbFileType.XML.toString())) {
throw new PdbException(
"\nInvalid file type (expecting .pdb or .pdb.xml): '" + pdbFilename + "'");
}
}
private void checkOSCompatibility() throws PdbException {
if (!isXML && !onWindows) {
throw new PdbException(
"\n.pdb files may only be loaded when running Windows. To load PDBs\n" +
"on other platforms, use Windows to pre-dump the .pdb file to .pdb.xml\n" +
"using 'CreatePdbXmlFilesScript.java' or 'createPdbXmlFiles.bat'.");
}
if (onWindows && isXML) {
Msg.warn(this,
"Could not find .pdb file in the classpath or the given Symbol Repository" +
" Directory. Using " + pdbFile.getAbsolutePath() + ", instead.");
}
}
private void checkPdbLoaded() throws PdbException {
if (isPdbLoaded()) {
throw new PdbException("PDB file has already been loaded.");
}
}
private boolean hasErrors() {
return thread != null && thread.hasErrors();
}
private boolean hasWarnings() {
return thread != null && thread.hasWarnings();
}
private String getErrorAndWarningMessages() {
return thread == null ? "" : thread.getErrorAndWarningMessages();
}
/**
* Open Windows Data Type Archives
*
* @throws IOException if an i/o error occurs opening the data type archive
* @throws Exception if any other error occurs
*/
public void openDataTypeArchives() throws IOException, Exception {
if (program != null) {
List<String> archiveList = DataTypeArchiveUtility.getArchiveList(program);
for (String string : archiveList) {
service.openDataTypeArchive(string);
}
}
// CLIB .gdt is now part of windows archive
// NTDDK has not been parsed
}
/**
* Configures the set of command line arguments for the pdb.exe process
* @param noValidation do not ask for GUID/Signature, Age validation
* @return the array of arguments for the command line
* @throws PdbException if the appropriate set of GUID/Signature, Age values is not available
*/
private String[] getCommandLineArray(boolean noValidation) throws PdbException {
File pdbExeFile;
String pdbExe = null;
try {
pdbExeFile = Application.getOSFile(PDB_EXE);
pdbExe = pdbExeFile.getAbsolutePath();
}
catch (FileNotFoundException e) {
throw new PdbException("Unable to find " + PDB_EXE);
}
if (noValidation) {
return new String[] { pdbExe, pdbFile.getAbsolutePath() };
}
String pdbAge = programAttributes.getPdbAge();
String pdbGuid = programAttributes.getPdbGuid();
String pdbSignature = programAttributes.getPdbSignature();
if (pdbAge != null && pdbGuid != null) {
return new String[] { pdbExe, pdbFile.getAbsolutePath(), pdbGuid, pdbAge };
}
if (pdbAge != null && pdbSignature != null) {
return new String[] { pdbExe, pdbFile.getAbsolutePath(), pdbSignature, pdbAge };
}
throw new PdbException("Unable to determine PDB GUID/Signature or Age. " +
"Please re-import the executable and try again.");
}
private void completeDefferedTypeParsing(ApplyDataTypes applyDataTypes,
ApplyTypeDefs applyTypeDefs, MessageLog log) throws CancelledException {
defineClasses(log);
if (applyDataTypes != null) {
applyDataTypes.buildDataTypes(monitor);
}
if (applyTypeDefs != null) {
applyTypeDefs.buildTypeDefs(monitor); // TODO: no dependencies exit on TypeDefs (use single pass)
}
// Ensure that all data types are resolved
if (dataTypeParser != null) {
dataTypeParser.flushDataTypeCache();
}
}
/**
* Apply PDB debug information to the current program
*
* @param log MessageLog used to record errors
* @throws IOException if an error occurs during parsing
* @throws PdbException if PDB file has already been loaded
* @throws CancelledException if user cancels the current action
*/
public void applyTo(MessageLog log) throws IOException, PdbException, CancelledException {
if (!parsed) {
throw new IOException("PDB: parse() must be called before applyTo()");
}
checkPdbLoaded();
errHandler.setMessageLog(log);
Msg.debug(this, "Found PDB for " + program.getName());
try {
ApplyDataTypes applyDataTypes = null;
ApplyTypeDefs applyTypeDefs = null;
boolean typesFlushed = false;
while (parser.hasNext()) {
if (hasErrors()) {
throw new IOException(getErrorAndWarningMessages());
}
if (monitor.isCancelled()) {
return;
}
XmlElement element = parser.next();
if (!element.isStart()) {
continue;
}
// long start = System.currentTimeMillis();
if (element.getName().equals("pdb")) {
/*
String exe = element.getAttribute("exe");
exe = (exe == null ? "" : exe.toLowerCase());
File exeFile = new File(program.getExecutablePath());
if (!exeFile.getName().toLowerCase().startsWith(exe)) {
throw new RuntimeException("'"+pdbFile.getName()+"' not valid for '"+exeFile.getName()+"'");
}
*/
}
else if (element.getName().equals("enums")) {
// apply enums - no data type dependencies
ApplyEnums.applyTo(parser, this, monitor, log);
}
else if (element.getName().equals("datatypes")) {
if (applyDataTypes == null) {
applyDataTypes = new ApplyDataTypes(this, log);
}
applyDataTypes.preProcessDataTypeList(parser, false, monitor);
}
else if (element.getName().equals("classes")) {
if (applyDataTypes == null) {
applyDataTypes = new ApplyDataTypes(this, log);
}
applyDataTypes.preProcessDataTypeList(parser, true, monitor);
}
else if (element.getName().equals("typedefs")) {
applyTypeDefs = new ApplyTypeDefs(this, parser, monitor, log);
}
else if (element.getName().equals("functions")) {
// apply functions (must occur within XML after all type sections)
if (!typesFlushed) {
completeDefferedTypeParsing(applyDataTypes, applyTypeDefs, log);
typesFlushed = true;
}
ApplyFunctions.applyTo(this, parser, monitor, log);
}
else if (element.getName().equals("tables")) {
// apply tables (must occur within XML after all other sections)
if (!typesFlushed) {
completeDefferedTypeParsing(applyDataTypes, applyTypeDefs, log);
typesFlushed = true;
}
ApplyTables.applyTo(this, parser, monitor, log);
}
// Msg.debug(this,
// element.getName().toUpperCase() + ": " + (System.currentTimeMillis() - start) +
// " ms");
}
if (!typesFlushed) {
completeDefferedTypeParsing(applyDataTypes, applyTypeDefs, log);
}
Options options = program.getOptions(Program.PROGRAM_INFO);
options.setBoolean(PdbParserConstants.PDB_LOADED, true);
if (dataTypeParser != null && dataTypeParser.hasMissingBitOffsetError()) {
log.error("PDB Parser",
"One or more bitfields were specified without bit-offset data.\nThe use of old pdb.xml data could be the cause.");
}
}
catch (CancelledException e) {
throw e;
}
catch (Exception e) {
// Exception could occur if a symbol element is missing an important attribute such
// as address or length
String message = e.getMessage();
if (message == null) {
message = e.getClass().getSimpleName();
}
message = "Problem parsing or applying PDB information: " + message;
Msg.error(this, message, e);
throw new IOException(message, e);
}
finally {
cleanup();
}
if (hasErrors()) {
throw new IOException(getErrorAndWarningMessages());
}
}
void predefineClass(String classname) {
SymbolPath classPath = new SymbolPath(classname);
namespaceMap.put(classPath, true);
for (SymbolPath path = classPath.getParent(); path != null; path = path.getParent()) {
if (!namespaceMap.containsKey(path)) {
namespaceMap.put(path, false); // path is simple namespace
}
}
}
private void defineClasses(MessageLog log) throws CancelledException {
// create namespace and classes in an ordered fashion use tree map
monitor.initialize(namespaceMap.size());
for (SymbolPath path : namespaceMap.keySet()) {
monitor.checkCanceled();
boolean isClass = namespaceMap.get(path);
Namespace parentNamespace =
NamespaceUtils.getNamespace(program, path.getParent(), null);
if (parentNamespace == null) {
String type = isClass ? "class" : "namespace";
log.appendMsg("Error: failed to define " + type + ": " + path);
continue;
}
defineNamespace(parentNamespace, path.getName(), isClass, log);
monitor.incrementProgress(1);
}
monitor.initialize(100);
}
private void defineNamespace(Namespace parentNamespace, String name, boolean isClass,
MessageLog log) {
try {
SymbolTable symbolTable = program.getSymbolTable();
Namespace namespace = symbolTable.getNamespace(name, parentNamespace);
if (namespace != null) {
if (isClass) {
if (namespace instanceof GhidraClass) {
return;
}
if (isSimpleNamespaceSymbol(namespace)) {
NamespaceUtils.convertNamespaceToClass(namespace);
return;
}
}
else if (namespace.getSymbol().getSymbolType() == SymbolType.NAMESPACE) {
return;
}
log.appendMsg("Unable to create class namespace due to conflicting symbol: " +
namespace.getName(true));
}
else if (isClass) {
symbolTable.createClass(parentNamespace, name, SourceType.IMPORTED);
}
else {
symbolTable.createNameSpace(parentNamespace, name, SourceType.IMPORTED);
}
}
catch (Exception e) {
log.appendMsg("Unable to create class namespace: " + parentNamespace.getName(true) +
Namespace.NAMESPACE_DELIMITER + name);
}
}
private boolean isSimpleNamespaceSymbol(Namespace namespace) {
Symbol s = namespace.getSymbol();
if (s.getSymbolType() != SymbolType.NAMESPACE) {
return false;
}
Namespace n = namespace;
while (n != null) {
if (n instanceof Function) {
return false;
}
n = n.getParentNamespace();
}
return true;
}
/**
* If it's a *.pdb file, pass it to the pdb.exe executable and get the stream storing
* the XML output.
*
* If it's a *.xml file, read the file into a stream and verify that the XML GUID/Signature and
* age match the program's GUID/Signature and age.
*
* @param skipValidation true if we should skip checking that GUID/Signature and age match
* @throws PdbException If issue running the pdb.exe process
* @throws IOException If an I/O error occurs
*/
private void processPdbContents(boolean skipValidation) throws PdbException, IOException {
InputStream in = null;
if (!isXML) {
String[] cmd = getCommandLineArray(skipValidation);
Runtime runtime = Runtime.getRuntime();
try {
// Note: we can't use process.waitFor() here, because the result of
// 'process.getInputStream()' is passed around and manipulated by
// the parser. In order for .waitFor() to work, the stream needs to
// be taken care of immediately so that the process can return. Currently,
// with the process' input stream getting passed around, the call to
// .waitFor() creates a deadlock condition.
process = runtime.exec(cmd);
}
catch (IOException e) {
if (e.getMessage().endsWith("14001")) {//missing runtime dlls, probably
throw new PdbException("Missing runtime libraries. " + "Please refer to " +
README_FILENAME + " and follow instructions.");
}
throw e;
}
in = process.getInputStream();
InputStream err = process.getErrorStream();
thread = new PdbErrorReaderThread(err);
thread.start();
}
else {
in = new FileInputStream(pdbFile);
}
errHandler = new PdbErrorHandler();
try {
parser = XmlPullParserFactory.create(in, pdbFile.getName(), errHandler, false);
}
catch (SAXException e) {
throw new IOException(e.getMessage());
}
}
/**
* Check to see if GUID and age in XML file matches GUID/Signature and age of binary
*
* @throws IOException If an I/O error occurs
* @throws PdbException If error parsing the PDB.XML data
*/
private void verifyPdbSignature() throws IOException, PdbException {
XmlElement xmlelem;
try {
xmlelem = parser.peek();
}
catch (Exception e) {
if (!isXML) {
if (hasErrors()) {
throw new PdbException(getErrorAndWarningMessages());
}
throw new PdbException("PDB Execution failure of " + PDB_EXE + ".\n" +
"This was likely caused by severe execution failure which can occur if executed\n" +
"on an unsupported platform. It may be neccessary to rebuild the PDB executable\n" +
"for your platform (see Ghidra/Features/PDB/src).");
}
throw new PdbException("PDB parsing problem: " + e.getMessage());
}
if (!"pdb".equals(xmlelem.getName())) {
throw new PdbException("Unexpected PDB XML element: " + xmlelem.getName());
}
String xmlGuid = xmlelem.getAttribute("guid");
String xmlAge = xmlelem.getAttribute("age");
String warning = "";
String pdbGuid = programAttributes.getPdbGuid();
if (pdbGuid == null) {
String pdbSignature = programAttributes.getPdbSignature();
if (pdbSignature != null) {
pdbGuid = reformatSignatureToGuidForm(pdbSignature);
}
}
String pdbAge = programAttributes.getPdbAge();
if ((xmlGuid == null) || (pdbGuid == null)) {
if (xmlGuid == null) {
warning += "No GUID was listed in the XML file.";
}
if (pdbGuid == null) {
warning += " Could not find a PDB GUID for the binary.";
}
warning += " Could not complete verification of matching PDB signatures.";
}
else {
// Reformat PDB GUID so that it matches the way GUIDs are stored in XML
pdbGuid = pdbGuid.toUpperCase();
pdbGuid = "{" + pdbGuid + "}";
if (!xmlGuid.equals(pdbGuid)) {
warning = "PDB signature does not match.";
}
else {
// Also check that PDB ages match, if they are both available
if ((xmlAge != null) && (pdbAge != null)) {
int pdbAgeDecimal = Integer.parseInt(pdbAge, 16);
int xmlAgeDecimal = Integer.parseInt(xmlAge);
if (xmlAgeDecimal != pdbAgeDecimal) {
warning = "PDB ages do not match.";
}
}
}
}
if (warning.length() > 0) {
if (SystemUtilities.isInHeadlessMode()) {
throw new PdbException(warning + ".. Skipping PDB processing.");
}
int option = OptionDialog.showYesNoDialog(null, "Continue Loading PDB?",
warning + "\n " + "\nContinue anyway?" + "\n " +
"\nPlease note: Invalid disassembly may be produced!");
if (option != OptionDialog.OPTION_ONE) {
throw new PdbException(warning);
}
}
}
/**
* Translate signature to GUID form. A signature is usually 8 characters long. A GUID
* has 32 characters and its subparts are separated by '-' characters.
*
* @param pdbSignature signature for conversion
* @return reformatted String
*/
private String reformatSignatureToGuidForm(String pdbSignature) {
// GUID structure (32 total hex chars):
// {8 hex}-{4 hex}-{4 hex}-{4 hex}-{12 hex}
//
// If PDB signature is less than 32 chars, make up the rest in 0's.
// If > 32 chars (which it should never be), just truncate to 32 chars
if (pdbSignature.length() > 32) {
pdbSignature = pdbSignature.substring(0, 32);
}
StringBuilder builder = new StringBuilder(pdbSignature);
for (int i = pdbSignature.length(); i < 32; i++) {
builder = builder.append('0');
}
// Insert '-' characters at the right boundaries
builder = builder.insert(8, '-').insert(13, '-').insert(18, '-').insert(23, '-');
return builder.toString();
}
/**
* Checks if PDB has been loaded in the program
*
* @return whether PDB has been loaded or not
*/
public boolean isPdbLoaded() {
return programAttributes.isPdbLoaded();
}
// TODO: verify this method is necessary
private void cleanup() {
if (process != null) {
process.destroy();
process = null;
}
if (parser != null) {
parser.dispose();
parser = null;
}
//errHandler = null;
//thread = null;
if (dataTypeParser != null) {
dataTypeParser.clear();
}
}
boolean isCorrectKind(DataType dt, PdbKind kind) {
if (kind == PdbKind.STRUCTURE) {
return (dt instanceof Structure);
}
else if (kind == PdbKind.UNION) {
return (dt instanceof Union);
}
return false;
}
Composite createComposite(PdbKind kind, String name) {
if (kind == PdbKind.STRUCTURE) {
return createStructure(name, 0);
}
else if (kind == PdbKind.UNION) {
return createUnion(name);
}
throw new IllegalArgumentException("unsupported kind: " + kind);
}
Structure createStructure(String name, int length) {
SymbolPath path = new SymbolPath(name);
return new StructureDataType(getCategory(path.getParent(), true), path.getName(), length,
dataMgr);
}
Union createUnion(String name) {
SymbolPath path = new SymbolPath(name);
return new UnionDataType(getCategory(path.getParent(), true), path.getName(), dataMgr);
}
TypedefDataType createTypeDef(String name, DataType baseDataType) {
SymbolPath path = new SymbolPath(name);
return new TypedefDataType(getCategory(path.getParent(), true), path.getName(),
baseDataType, dataMgr);
}
EnumDataType createEnum(String name, int length) {
SymbolPath path = new SymbolPath(name);
return new EnumDataType(getCategory(path.getParent(), true), path.getName(), length,
dataMgr);
}
void createString(boolean isUnicode, Address address, MessageLog log) {
DataType dataType = isUnicode ? new UnicodeDataType() : new StringDataType();
createData(address, dataType, log);
}
void createData(Address address, String datatype, MessageLog log) throws CancelledException {
WrappedDataType wrappedDt = getDataTypeParser().findDataType(datatype);
if (wrappedDt == null) {
log.appendMsg("Error: Failed to resolve datatype " + datatype + " at " + address);
}
else if (wrappedDt.isZeroLengthArray()) {
Msg.debug(this, "Did not apply zero length array data " + datatype + " at " + address);
}
else {
createData(address, wrappedDt.getDataType(), log);
}
}
void createData(Address address, DataType dataType, MessageLog log) {
DumbMemBufferImpl memBuffer = new DumbMemBufferImpl(program.getMemory(), address);
DataTypeInstance dti = DataTypeInstance.getDataTypeInstance(dataType, memBuffer);
if (dti == null) {
log.appendMsg(
"Error: Failed to apply datatype " + dataType.getName() + " at " + address);
}
else {
createData(address, dti.getDataType(), dti.getLength(), log);
}
}
private void createData(Address address, DataType dataType, int dataTypeLength,
MessageLog log) {
// Ensure that we do not clear previously established code and data
Data existingData = null;
CodeUnit cu = program.getListing().getCodeUnitContaining(address);
if (cu != null) {
if ((cu instanceof Instruction) || !address.equals(cu.getAddress())) {
log.appendMsg("Warning: Did not create data type \"" + dataType.getDisplayName() +
"\" at address " + address + " due to conflict");
return;
}
Data d = (Data) cu;
if (d.isDefined()) {
existingData = d;
}
}
if (dataType == null) {
return;
}
if (dataType.getLength() <= 0 && dataTypeLength <= 0) {
log.appendMsg("Unknown dataTypeLength specified at address " + address + " for " +
dataType.getName());
return;
}
// TODO: This is really bad logic and should be refactored
// All conflicting data, not just the one containing address,
// needs to be considered and not blindly cleared.
if (existingData != null) {
DataType existingDataType = existingData.getDataType();
if (isEquivalent(existingData, existingData.getLength(), dataType)) {
return;
}
if (isEquivalent2(existingDataType, dataType)) {
return;
}
if (existingDataType.isEquivalent(dataType)) {
return;
}
}
Listing listing = program.getListing();
if (existingData == null) {
try {
listing.clearCodeUnits(address, address.add(dataTypeLength - 1), false);
if (dataType.getLength() == -1) {
listing.createData(address, dataType, dataTypeLength);
}
else {
listing.createData(address, dataType);
}
}
catch (Exception e) {
log.appendMsg("Unable to create " + dataType.getDisplayName() + " at 0x" + address +
": " + e.getMessage());
}
}
else if (isDataReplaceable(existingData)) {
try {
listing.clearCodeUnits(address, address.add(dataTypeLength - 1), false);
listing.createData(address, dataType, dataTypeLength);
}
catch (Exception e) {
log.appendMsg("Unable to replace " + dataType.getDisplayName() + " at 0x" +
address + ": " + e.getMessage());
}
}
else {
DataType existingDataType = existingData.getDataType();
String existingDataTypeString =
existingDataType == null ? "null" : existingDataType.getDisplayName();
log.appendMsg("Warning: Did not create data type \"" + dataType.getDisplayName() +
"\" at address " + address + ". Preferring existing datatype \"" +
existingDataTypeString + "\"");
}
}
private boolean isDataReplaceable(Data data) {
DataType dataType = data.getDataType();
if (dataType instanceof Pointer) {
Pointer pointer = (Pointer) dataType;
DataType pointerDataType = pointer.getDataType();
if (pointerDataType == null || pointerDataType.isEquivalent(DataType.DEFAULT)) {
return true;
}
}
else if (dataType instanceof Array) {
Array array = (Array) dataType;
DataType arrayDataType = array.getDataType();
if (arrayDataType == null || arrayDataType.isEquivalent(DataType.DEFAULT)) {
return true;
}
}
// All forms of Undefined data are replaceable
// TODO: maybe it should check the length of the data type before putting it down.
if (Undefined.isUndefined(dataType)) {
return true;
}
return false;
}
private boolean isEquivalent(Data existingData, int existingDataTypeLength,
DataType newDataType) {
if (existingData.hasStringValue()) {
if (newDataType instanceof ArrayDataType) {
Array array = (Array) newDataType;
DataType arrayDataType = array.getDataType();
if (arrayDataType instanceof ArrayStringable) {
if (array.getLength() == existingDataTypeLength) {
return true;
}
}
}
}
return false;
}
/**
* "char[12] *" "char * *"
*
* "ioinfo * *" "ioinfo[64] *"
*/
private boolean isEquivalent2(DataType datatype1, DataType datatype2) {
if (datatype1 == datatype2) {
return true;
}
if (datatype1 == null || datatype2 == null) {
return false;
}
if (datatype1 instanceof Array) {
Array array1 = (Array) datatype1;
if (datatype2 instanceof Array) {
Array array2 = (Array) datatype2;
return isEquivalent2(array1.getDataType(), array2.getDataType());
}
}
else if (datatype1 instanceof Pointer) {
Pointer pointer1 = (Pointer) datatype1;
if (datatype2 instanceof Array) {
Array array2 = (Array) datatype2;
return isEquivalent2(pointer1.getDataType(), array2.getDataType());
}
}
return datatype1.isEquivalent(datatype2);
}
boolean createSymbol(Address address, String symbolPathString, boolean forcePrimary,
MessageLog log) {
try {
Namespace namespace = program.getGlobalNamespace();
SymbolPath symbolPath = new SymbolPath(symbolPathString);
symbolPath = symbolPath.replaceInvalidChars();
String name = symbolPath.getName();
String namespacePath = symbolPath.getParentPath();
if (namespacePath != null) {
namespace = NamespaceUtils.createNamespaceHierarchy(namespacePath, namespace,
program, address, SourceType.IMPORTED);
}
Symbol s = SymbolUtilities.createPreferredLabelOrFunctionSymbol(program, address,
namespace, name, SourceType.IMPORTED);
if (s != null && forcePrimary) {
// PDB contains both mangled, namespace names, and global names
// If mangled name does not remain primary it will not get demamgled
// and we may not get signature information applied
SetLabelPrimaryCmd cmd =
new SetLabelPrimaryCmd(address, s.getName(), s.getParentNamespace());
cmd.applyTo(program);
}
return true;
}
catch (InvalidInputException e) {
log.appendMsg("Unable to create symbol: " + e.getMessage());
}
return false;
}
// DataType createPointer(DataType dt) {
// return PointerDataType.getPointer(dt, program.getDataTypeManager());
// }
// DataType getCachedDataType(String key) {
// return dataTypeCache.get(key);
// }
//
// void cacheDataType(String key, DataType dataType) {
// dataTypeCache.put(key, dataType);
// }
/**
* Get the PDB root category path
* @return PDB root category path
*/
CategoryPath getCategory() {
return pdbCategory;
}
/**
* Get the name with any namespace stripped
* @param name name with optional namespace prefix
* @return name without namespace prefix
*/
String stripNamespace(String name) {
int index = name.lastIndexOf(Namespace.NAMESPACE_DELIMITER);
if (index <= 0) {
return name;
}
return name.substring(index + Namespace.NAMESPACE_DELIMITER.length());
}
/**
* Get the category path associated with the namespace qualified data type name
* @param namespaceQualifiedDataTypeName data type name
* @param addPdbRoot true if PDB root category should be used, otherwise it will be omitted
* @return the category path
*/
CategoryPath getCategory(String namespaceQualifiedDataTypeName, boolean addPdbRoot) {
String[] names = namespaceQualifiedDataTypeName.split(Namespace.NAMESPACE_DELIMITER);
CategoryPath category = addPdbRoot ? pdbCategory : CategoryPath.ROOT;
if (names.length > 1) {
String[] categoryNames = new String[names.length - 1];
System.arraycopy(names, 0, categoryNames, 0, categoryNames.length);
for (String c : categoryNames) {
category = new CategoryPath(category, c);
}
}
return category;
}
/**
* Get the {@link CategoryPath} associated with the namespace specified by the
* {@link SymbolPath}, rooting it either at the Category Path root or the PDB Category.
* @param symbolPath the {@link SymbolPath} input; can be null if no depth in path.
* @param addPdbRoot True if PDB root category should be used, otherwise it will be omitted.
* @return {@link CategoryPath} created for the input.
*/
CategoryPath getCategory(SymbolPath symbolPath, boolean addPdbRoot) {
CategoryPath category = addPdbRoot ? pdbCategory : CategoryPath.ROOT;
if (symbolPath != null) {
List<String> names = symbolPath.asList();
for (String name : names) {
category = new CategoryPath(category, name);
}
}
return category;
}
/********************************************************************/
/* STATIC METHODS */
/********************************************************************/
/**
* Get the object that stores PDB-related attributes for the program.
*
* @param program program for which to find a matching PDB
* @return PDBProgramAttributes object associated with the program
*/
public static PdbProgramAttributes getPdbAttributes(Program program) {
return new PdbProgramAttributes(program);
}
/**
* Find the PDB associated with the given program using its attributes
*
* @param program program for which to find a matching PDB
* @return matching PDB for program, or null
* @throws PdbException if there was a problem with the PDB attributes
*/
public static File findPDB(Program program) throws PdbException {
return findPDB(getPdbAttributes(program), false, null, null);
}
/**
* Determine if the PDB has previously been loaded for the specified program.
* @param program program for which to find a matching PDB
* @return true if PDB has already been loaded
*/
public static boolean isAlreadyLoaded(Program program) {
return getPdbAttributes(program).isPdbLoaded();
}
/**
* Find the PDB associated with the given program using its attributes, specifying the
* location where symbols are stored.
*
* @param program program for which to find a matching PDB
* @param includePeSpecifiedPdbPath to also check the PE-header-specified PDB path
* @param symbolsRepositoryPath location where downloaded symbols are stored
* @return matching PDB for program, or null
* @throws PdbException if there was a problem with the PDB attributes
*/
public static File findPDB(Program program, boolean includePeSpecifiedPdbPath,
String symbolsRepositoryPath) throws PdbException {
return findPDB(getPdbAttributes(program), includePeSpecifiedPdbPath, symbolsRepositoryPath,
null);
}
/**
* Find a matching PDB file using attributes associated with the program. User can specify the
* type of file to search from (.pdb or .pdb.xml).
*
* @param pdbAttributes PDB attributes associated with the program
* @param includePeSpecifiedPdbPath to also check the PE-header-specified PDB path
* @param symbolsRepositoryPath location of the local symbols repository (can be null)
* @param fileType type of file to search for (can be null)
* @return matching PDB file (or null, if not found)
* @throws PdbException if there was a problem with the PDB attributes
*/
public static File findPDB(PdbProgramAttributes pdbAttributes,
boolean includePeSpecifiedPdbPath, String symbolsRepositoryPath, PdbFileType fileType)
throws PdbException {
// Store potential names of PDB files and potential locations of those files,
// so that all possible combinations can be searched.
// LinkedHashSet is used when we need to preserve order
Set<String> guidSubdirPaths = new HashSet<>();
String guidAgeString = pdbAttributes.getGuidAgeCombo();
if (guidAgeString == null) {
throw new PdbException(
"Incomplete PDB information (GUID/Signature and/or age) associated with this program.\n" +
"Either the program is not a PE, or it was not compiled with debug information.");
}
List<String> potentialPdbNames = pdbAttributes.getPotentialPdbFilenames();
for (String potentialName : potentialPdbNames) {
guidSubdirPaths.add(File.separator + potentialName + File.separator + guidAgeString);
}
return checkPathsForPdb(symbolsRepositoryPath, guidSubdirPaths, potentialPdbNames, fileType,
pdbAttributes, includePeSpecifiedPdbPath);
}
/**
* Check potential paths in a specific order. If the symbolsRepositoryPath parameter is
* supplied and the directory exists, that directory will be searched first for the
* matching PDB file.
*
* If the file type is supplied, then only that file type will be searched for. Otherwise,
* the search process depends on the current operating system that Ghidra is running from:
*
* - Windows: look in the symbolsRepositoryPath for a matching .pdb file. If one does not
* exist, look for a .pdb.xml file in symbolsRepositoryPath. If not found, then
* search for a matching .pdb file, then .pdb.xml file, in other directories.
* - non-Windows: look in the symbolsRepositoryPath for a matching .pdb.xml file. If one does
* not exist, look for a .pdb file. If a .pdb file is found, return an error saying
* that it was found, but could not be processed. If no matches found in
* symbolsRepositoryPath, then look for .pdb.xml file, then .pdb.xml file in other
* directories.
*
* @param symbolsRepositoryPath location of the local symbols repository (can be null)
* @param guidSubdirPaths subdirectory paths (that include the PDB's GUID) that may contain
* a matching PDB
* @param potentialPdbNames all potential filenames for the PDB file(s) that match the program
* @param fileType file type to search for (can be null)
* @param pdbAttributes PDB attributes associated with the program
* @return matching PDB file, if found (else null)
*/
private static File checkPathsForPdb(String symbolsRepositoryPath, Set<String> guidSubdirPaths,
List<String> potentialPdbNames, PdbFileType fileType,
PdbProgramAttributes pdbAttributes, boolean includePeSpecifiedPdbPath) {
File foundPdb = null;
Set<File> symbolsRepoPaths =
getSymbolsRepositoryPaths(symbolsRepositoryPath, guidSubdirPaths);
Set<File> predefinedPaths =
getPredefinedPaths(guidSubdirPaths, pdbAttributes, includePeSpecifiedPdbPath);
boolean fileTypeSpecified = (fileType != null), checkForXml;
// If the file type is specified, look for that type of file only.
if (fileTypeSpecified) {
checkForXml = (fileType == PdbFileType.XML) ? true : false;
foundPdb = checkForPDBorXML(symbolsRepoPaths, potentialPdbNames, checkForXml);
if (foundPdb != null) {
return foundPdb;
}
foundPdb = checkForPDBorXML(predefinedPaths, potentialPdbNames, checkForXml);
return foundPdb;
}
// If the file type is not specified, look for both file types, starting with the
// file type that's most appropriate for the Operating System (PDB for Windows, XML for
// non-Windows).
checkForXml = onWindows ? false : true;
// Start by searching in symbolsRepositoryPath, if available.
if (symbolsRepositoryPath != null) {
foundPdb = checkSpecificPathsForPdb(symbolsRepoPaths, potentialPdbNames, checkForXml);
}
if (foundPdb != null) {
return foundPdb;
}
return checkSpecificPathsForPdb(predefinedPaths, potentialPdbNames, checkForXml);
}
private static File checkSpecificPathsForPdb(Set<File> paths, List<String> potentialPdbNames,
boolean checkForXmlFirst) {
File foundPdb = checkForPDBorXML(paths, potentialPdbNames, checkForXmlFirst);
if (foundPdb != null) {
return foundPdb;
}
foundPdb = checkForPDBorXML(paths, potentialPdbNames, !checkForXmlFirst);
return foundPdb;
}
private static Set<File> getSymbolsRepositoryPaths(String symbolsRepositoryPath,
Set<String> guidSubdirPaths) {
Set<File> symbolsRepoPaths = new LinkedHashSet<>();
// Collect sub-directories of the symbol repository that exist
File symRepoFile;
if (symbolsRepositoryPath != null &&
(symRepoFile = new File(symbolsRepositoryPath)).isDirectory()) {
for (String guidSubdir : guidSubdirPaths) {
File testDir = new File(symRepoFile, guidSubdir);
if (testDir.isDirectory()) {
symbolsRepoPaths.add(testDir);
}
}
// Check outer folder last
symbolsRepoPaths.add(symRepoFile);
}
return symbolsRepoPaths;
}
// Get list of "paths we know about" to search for PDBs
private static Set<File> getPredefinedPaths(Set<String> guidSubdirPaths,
PdbProgramAttributes pdbAttributes, boolean includePeSpecifiedPdbPath) {
Set<File> predefinedPaths = new LinkedHashSet<>();
getPathsFromAttributes(pdbAttributes, includePeSpecifiedPdbPath, predefinedPaths);
getWindowsPaths(guidSubdirPaths, predefinedPaths);
getLibraryPaths(guidSubdirPaths, predefinedPaths);
return predefinedPaths;
}
private static void getLibraryPaths(Set<String> guidSubdirPaths, Set<File> predefinedPaths) {
String[] libraryPaths = LibrarySearchPathManager.getLibraryPaths();
File libFile, subDir;
for (String path : libraryPaths) {
if ((libFile = new File(path)).isDirectory()) {
predefinedPaths.add(libFile);
// Check alternate locations
for (String guidSubdir : guidSubdirPaths) {
if ((subDir = new File(path, guidSubdir)).isDirectory()) {
predefinedPaths.add(subDir);
}
}
}
}
}
private static void getWindowsPaths(Set<String> guidSubdirPaths, Set<File> predefinedPaths) {
// Don't have to call .exists(), since .isDirectory() does that already
if (onWindows && SPECIAL_PDB_LOCATION.isDirectory()) {
predefinedPaths.add(SPECIAL_PDB_LOCATION);
// Check alternate locations
String specialPdbPath = SPECIAL_PDB_LOCATION.getAbsolutePath();
for (String guidSubdir : guidSubdirPaths) {
File testDir = new File(specialPdbPath + guidSubdir);
if (testDir.isDirectory()) {
predefinedPaths.add(testDir);
}
}
}
}
private static void getPathsFromAttributes(PdbProgramAttributes pdbAttributes,
boolean includePeSpecifiedPdbPath, Set<File> predefinedPaths) {
if (pdbAttributes != null) {
String currentPath = pdbAttributes.getPdbFile();
if (currentPath != null && includePeSpecifiedPdbPath) {
File parentDir = new File(currentPath).getParentFile();
if (parentDir != null && parentDir.exists()) {
predefinedPaths.add(parentDir);
}
}
currentPath = pdbAttributes.getExecutablePath();
if (currentPath != null && !currentPath.equals("unknown")) {
File parentDir = new File(currentPath).getParentFile();
if (parentDir != null && parentDir.exists()) {
predefinedPaths.add(parentDir);
}
}
}
}
/**
* Returns the first PDB-type file found. Assumes list of potentialPdbDirs is in the order
* in which the directories should be searched.
*
* @param potentialPdbDirs potential PDB directories
* @param potentialPdbNames potential PDB names
* @param findXML - if true, only searches for the .pdb.xml version of the .pdb file
* @return the first file found
*/
private static File checkForPDBorXML(Set<File> potentialPdbDirs, List<String> potentialPdbNames,
boolean findXML) {
File pdb;
for (File pdbPath : potentialPdbDirs) {
for (String filename : potentialPdbNames) {
if (findXML) {
pdb = new File(pdbPath, filename + PdbFileType.XML.toString());
}
else {
pdb = new File(pdbPath, filename);
}
// Note: isFile() also checks for existence
if (pdb.isFile()) {
return pdb;
}
}
}
return null;
}
PdbDataTypeParser getDataTypeParser() {
if (program == null) {
throw new AssertException("Parser was not constructed with program");
}
if (dataTypeParser == null) {
dataTypeParser = new PdbDataTypeParser(program.getDataTypeManager(), service, monitor);
}
return dataTypeParser;
}
void cacheDataType(String name, DataType dataType) {
getDataTypeParser().cacheDataType(name, dataType);
}
DataType getCachedDataType(String name) {
return getDataTypeParser().getCachedDataType(name);
}
void addDataType(DataType dataType) {
getDataTypeParser().addDataType(dataType);
}
WrappedDataType findDataType(String dataTypeName) throws CancelledException {
return getDataTypeParser().findDataType(dataTypeName);
}
public PdbMember getPdbXmlMember(XmlTreeNode node) {
return new PdbXmlMember(node);
}
public PdbXmlMember getPdbXmlMember(XmlElement element) {
return new PdbXmlMember(element);
}
class PdbXmlMember extends DefaultPdbMember {
PdbXmlMember(XmlTreeNode node) {
this(node.getStartElement());
}
PdbXmlMember(XmlElement element) {
super(SymbolUtilities.replaceInvalidChars(element.getAttribute("name"), false),
element.getAttribute("datatype"),
XmlUtilities.parseInt(element.getAttribute("offset")),
PdbKind.parse(element.getAttribute("kind")), getDataTypeParser());
}
}
}
| Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb/PdbParser.java | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.util.bin.format.pdb;
import java.io.*;
import java.util.*;
import org.xml.sax.SAXException;
import docking.widgets.OptionDialog;
import ghidra.app.cmd.label.SetLabelPrimaryCmd;
import ghidra.app.plugin.core.datamgr.util.DataTypeArchiveUtility;
import ghidra.app.services.DataTypeManagerService;
import ghidra.app.util.NamespaceUtils;
import ghidra.app.util.SymbolPath;
import ghidra.app.util.importer.LibrarySearchPathManager;
import ghidra.app.util.importer.MessageLog;
import ghidra.framework.*;
import ghidra.framework.options.Options;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.mem.DumbMemBufferImpl;
import ghidra.program.model.symbol.*;
import ghidra.util.Msg;
import ghidra.util.SystemUtilities;
import ghidra.util.exception.*;
import ghidra.util.task.TaskMonitor;
import ghidra.util.xml.XmlUtilities;
import ghidra.xml.*;
/**
* Contains methods for finding .pdb files and parsing them.
*/
public class PdbParser {
private static final String PDB_EXE = "pdb.exe";
private static final String README_FILENAME =
Application.getInstallationDirectory() + "\\docs\\README_PDB.html";
public final static File SPECIAL_PDB_LOCATION = new File("C:/WINDOWS/Symbols");
public final static String PDB_STORAGE_PROPERTY = "PDB Storage Directory";
static final String STRUCTURE_KIND = "Structure";
static final String UNION_KIND = "Union";
public final static boolean onWindows =
(Platform.CURRENT_PLATFORM.getOperatingSystem() == OperatingSystem.WINDOWS);
public enum PdbFileType {
PDB, XML;
@Override
public String toString() {
return "." + name().toLowerCase();
}
}
private TaskMonitor monitor;
private final boolean forceAnalysis;
private final File pdbFile;
private final boolean isXML;
private final Program program;
private DataTypeManager dataMgr;
private final DataTypeManagerService service;
private final PdbProgramAttributes programAttributes;
private Process process;
private XmlPullParser parser;
private PdbErrorHandler errHandler;
private PdbErrorReaderThread thread;
private boolean parsed = false;
private CategoryPath pdbCategory;
/**
* Note that the current implementation relies on having all types which are defined
* by the PDB to be available within the dataTypeCache using namespace-based type
* names.
*/
private PdbDataTypeParser dataTypeParser;
private Map<SymbolPath, Boolean> namespaceMap = new TreeMap<>(); // false: simple namespace, true: class namespace
public PdbParser(File pdbFile, Program program, DataTypeManagerService service,
boolean forceAnalysis, TaskMonitor monitor) {
this(pdbFile, program, service, getPdbAttributes(program), forceAnalysis, monitor);
}
public PdbParser(File pdbFile, Program program, DataTypeManagerService service,
PdbProgramAttributes programAttributes, boolean forceAnalysis, TaskMonitor monitor) {
this.pdbFile = pdbFile;
this.pdbCategory = new CategoryPath(CategoryPath.ROOT, pdbFile.getName());
this.program = program;
this.dataMgr = program.getDataTypeManager();
this.service = service;
this.forceAnalysis = forceAnalysis;
this.monitor = monitor != null ? monitor : TaskMonitor.DUMMY;
this.isXML = pdbFile.getAbsolutePath().endsWith(PdbFileType.XML.toString());
this.programAttributes = programAttributes;
}
/**
* Get the program's data type manager
* @return data type manager
*/
DataTypeManager getProgramDataTypeManager() {
return dataMgr;
}
/**
* Get the program associated with this parser
* @return program
*/
Program getProgram() {
return program;
}
/**
* Parse the PDB file, enforcing pre-conditions and post-conditions.
*
* @throws IOException If an I/O error occurs
* @throws PdbException if there was a problem during processing
*/
public void parse() throws IOException, PdbException {
checkPdbLoaded();
checkFileType();
checkOSCompatibility();
if (!forceAnalysis && !programAttributes.isProgramAnalyzed()) {
throw new PdbException("Before loading a PDB, you must first analyze the program.");
}
processPdbContents(false);
// The below code only applies when we are processing .pdb (not .pdb.xml) files
if (!isXML) {
try {//give thread sometime to spin up...
Thread.sleep(1000);
}
catch (Exception e) {
// don't care
}
if (hasErrors()) {
throw new PdbException(getErrorAndWarningMessages());
}
if (hasWarnings()) {
if (SystemUtilities.isInHeadlessMode()) {
throw new PdbException(
getErrorAndWarningMessages() + ".. Skipping PDB processing.");
}
int option = OptionDialog.showYesNoDialog(null, "Continue Loading PDB?",
getErrorAndWarningMessages() + "\n " + "\nContinue anyway?" + "\n " +
"\nPlease note: Invalid disassembly may be produced!");
if (option == OptionDialog.OPTION_ONE) {
cleanup();
processPdbContents(true);//attempt without validation...
}
else {
throw new PdbException(getErrorAndWarningMessages());
}
}
}
parsed = true;
}
private void checkFileType() throws PdbException {
String pdbFilename = pdbFile.getName();
if (!pdbFilename.endsWith(PdbFileType.PDB.toString()) &&
!pdbFilename.endsWith(PdbFileType.XML.toString())) {
throw new PdbException(
"\nInvalid file type (expecting .pdb or .pdb.xml): '" + pdbFilename + "'");
}
}
private void checkOSCompatibility() throws PdbException {
if (!isXML && !onWindows) {
throw new PdbException(
"\n.pdb files may only be loaded when running Windows. To load PDBs\n" +
"on other platforms, use Windows to pre-dump the .pdb file to .pdb.xml\n" +
"using 'CreatePdbXmlFilesScript.java' or 'createPdbXmlFiles.bat'.");
}
if (onWindows && isXML) {
Msg.warn(this,
"Could not find .pdb file in the classpath or the given Symbol Repository" +
" Directory. Using " + pdbFile.getAbsolutePath() + ", instead.");
}
}
private void checkPdbLoaded() throws PdbException {
if (isPdbLoaded()) {
throw new PdbException("PDB file has already been loaded.");
}
}
private boolean hasErrors() {
return thread != null && thread.hasErrors();
}
private boolean hasWarnings() {
return thread != null && thread.hasWarnings();
}
private String getErrorAndWarningMessages() {
return thread == null ? "" : thread.getErrorAndWarningMessages();
}
/**
* Open Windows Data Type Archives
*
* @throws IOException if an i/o error occurs opening the data type archive
* @throws Exception if any other error occurs
*/
public void openDataTypeArchives() throws IOException, Exception {
if (program != null) {
List<String> archiveList = DataTypeArchiveUtility.getArchiveList(program);
for (String string : archiveList) {
service.openDataTypeArchive(string);
}
}
// CLIB .gdt is now part of windows archive
// NTDDK has not been parsed
}
/**
* Configures the set of command line arguments for the pdb.exe process
* @param noValidation do not ask for GUID/Signature, Age validation
* @return the array of arguments for the command line
* @throws PdbException if the appropriate set of GUID/Signature, Age values is not available
*/
private String[] getCommandLineArray(boolean noValidation) throws PdbException {
File pdbExeFile;
String pdbExe = null;
try {
pdbExeFile = Application.getOSFile(PDB_EXE);
pdbExe = pdbExeFile.getAbsolutePath();
}
catch (FileNotFoundException e) {
throw new PdbException("Unable to find " + PDB_EXE);
}
if (noValidation) {
return new String[] { pdbExe, pdbFile.getAbsolutePath() };
}
String pdbAge = programAttributes.getPdbAge();
String pdbGuid = programAttributes.getPdbGuid();
String pdbSignature = programAttributes.getPdbSignature();
if (pdbAge != null && pdbGuid != null) {
return new String[] { pdbExe, pdbFile.getAbsolutePath(), pdbGuid, pdbAge };
}
if (pdbAge != null && pdbSignature != null) {
return new String[] { pdbExe, pdbFile.getAbsolutePath(), pdbSignature, pdbAge };
}
throw new PdbException("Unable to determine PDB GUID/Signature or Age. " +
"Please re-import the executable and try again.");
}
private void completeDefferedTypeParsing(ApplyDataTypes applyDataTypes,
ApplyTypeDefs applyTypeDefs, MessageLog log) throws CancelledException {
defineClasses(log);
if (applyDataTypes != null) {
applyDataTypes.buildDataTypes(monitor);
}
if (applyTypeDefs != null) {
applyTypeDefs.buildTypeDefs(monitor); // TODO: no dependencies exit on TypeDefs (use single pass)
}
// Ensure that all data types are resolved
if (dataTypeParser != null) {
dataTypeParser.flushDataTypeCache();
}
}
/**
* Apply PDB debug information to the current program
*
* @param log MessageLog used to record errors
* @throws IOException if an error occurs during parsing
* @throws PdbException if PDB file has already been loaded
* @throws CancelledException if user cancels the current action
*/
public void applyTo(MessageLog log) throws IOException, PdbException, CancelledException {
if (!parsed) {
throw new IOException("PDB: parse() must be called before applyTo()");
}
checkPdbLoaded();
errHandler.setMessageLog(log);
Msg.debug(this, "Found PDB for " + program.getName());
try {
ApplyDataTypes applyDataTypes = null;
ApplyTypeDefs applyTypeDefs = null;
boolean typesFlushed = false;
while (parser.hasNext()) {
if (hasErrors()) {
throw new IOException(getErrorAndWarningMessages());
}
if (monitor.isCancelled()) {
return;
}
XmlElement element = parser.next();
if (!element.isStart()) {
continue;
}
// long start = System.currentTimeMillis();
if (element.getName().equals("pdb")) {
/*
String exe = element.getAttribute("exe");
exe = (exe == null ? "" : exe.toLowerCase());
File exeFile = new File(program.getExecutablePath());
if (!exeFile.getName().toLowerCase().startsWith(exe)) {
throw new RuntimeException("'"+pdbFile.getName()+"' not valid for '"+exeFile.getName()+"'");
}
*/
}
else if (element.getName().equals("enums")) {
// apply enums - no data type dependencies
ApplyEnums.applyTo(parser, this, monitor, log);
}
else if (element.getName().equals("datatypes")) {
if (applyDataTypes == null) {
applyDataTypes = new ApplyDataTypes(this, log);
}
applyDataTypes.preProcessDataTypeList(parser, false, monitor);
}
else if (element.getName().equals("classes")) {
if (applyDataTypes == null) {
applyDataTypes = new ApplyDataTypes(this, log);
}
applyDataTypes.preProcessDataTypeList(parser, true, monitor);
}
else if (element.getName().equals("typedefs")) {
applyTypeDefs = new ApplyTypeDefs(this, parser, monitor, log);
}
else if (element.getName().equals("functions")) {
// apply functions (must occur within XML after all type sections)
if (!typesFlushed) {
completeDefferedTypeParsing(applyDataTypes, applyTypeDefs, log);
typesFlushed = true;
}
ApplyFunctions.applyTo(this, parser, monitor, log);
}
else if (element.getName().equals("tables")) {
// apply tables (must occur within XML after all other sections)
if (!typesFlushed) {
completeDefferedTypeParsing(applyDataTypes, applyTypeDefs, log);
typesFlushed = true;
}
ApplyTables.applyTo(this, parser, monitor, log);
}
// Msg.debug(this,
// element.getName().toUpperCase() + ": " + (System.currentTimeMillis() - start) +
// " ms");
}
if (!typesFlushed) {
completeDefferedTypeParsing(applyDataTypes, applyTypeDefs, log);
}
Options options = program.getOptions(Program.PROGRAM_INFO);
options.setBoolean(PdbParserConstants.PDB_LOADED, true);
if (dataTypeParser != null && dataTypeParser.hasMissingBitOffsetError()) {
log.error("PDB Parser",
"One or more bitfields were specified without bit-offset data.\nThe use of old pdb.xml data could be the cause.");
}
}
catch (CancelledException e) {
throw e;
}
catch (Exception e) {
// Exception could occur if a symbol element is missing an important attribute such
// as address or length
String message = e.getMessage();
if (message == null) {
message = e.getClass().getSimpleName();
}
message = "Problem parsing or applying PDB information: " + message;
Msg.error(this, message, e);
throw new IOException(message, e);
}
finally {
cleanup();
}
if (hasErrors()) {
throw new IOException(getErrorAndWarningMessages());
}
}
void predefineClass(String classname) {
SymbolPath classPath = new SymbolPath(classname);
namespaceMap.put(classPath, true);
for (SymbolPath path = classPath.getParent(); path != null; path = path.getParent()) {
if (!namespaceMap.containsKey(path)) {
namespaceMap.put(path, false); // path is simple namespace
}
}
}
private void defineClasses(MessageLog log) throws CancelledException {
// create namespace and classes in an ordered fashion use tree map
monitor.initialize(namespaceMap.size());
for (SymbolPath path : namespaceMap.keySet()) {
monitor.checkCanceled();
boolean isClass = namespaceMap.get(path);
Namespace parentNamespace =
NamespaceUtils.getNamespace(program, path.getParent(), null);
if (parentNamespace == null) {
String type = isClass ? "class" : "namespace";
log.appendMsg("Error: failed to define " + type + ": " + path);
continue;
}
defineNamespace(parentNamespace, path.getName(), isClass, log);
monitor.incrementProgress(1);
}
monitor.initialize(100);
}
private void defineNamespace(Namespace parentNamespace, String name, boolean isClass,
MessageLog log) {
try {
SymbolTable symbolTable = program.getSymbolTable();
Namespace namespace = symbolTable.getNamespace(name, parentNamespace);
if (namespace != null) {
if (isClass) {
if (namespace instanceof GhidraClass) {
return;
}
if (isSimpleNamespaceSymbol(namespace)) {
NamespaceUtils.convertNamespaceToClass(namespace);
return;
}
}
else if (namespace.getSymbol().getSymbolType() == SymbolType.NAMESPACE) {
return;
}
log.appendMsg("Unable to create class namespace due to conflicting symbol: " +
namespace.getName(true));
}
else if (isClass) {
symbolTable.createClass(parentNamespace, name, SourceType.IMPORTED);
}
else {
symbolTable.createNameSpace(parentNamespace, name, SourceType.IMPORTED);
}
}
catch (Exception e) {
log.appendMsg("Unable to create class namespace: " + parentNamespace.getName(true) +
Namespace.NAMESPACE_DELIMITER + name);
}
}
private boolean isSimpleNamespaceSymbol(Namespace namespace) {
Symbol s = namespace.getSymbol();
if (s.getSymbolType() != SymbolType.NAMESPACE) {
return false;
}
Namespace n = namespace;
while (n != null) {
if (n instanceof Function) {
return false;
}
n = n.getParentNamespace();
}
return true;
}
/**
* If it's a *.pdb file, pass it to the pdb.exe executable and get the stream storing
* the XML output.
*
* If it's a *.xml file, read the file into a stream and verify that the XML GUID/Signature and
* age match the program's GUID/Signature and age.
*
* @param skipValidation true if we should skip checking that GUID/Signature and age match
* @throws PdbException If issue running the pdb.exe process
* @throws IOException If an I/O error occurs
*/
private void processPdbContents(boolean skipValidation) throws PdbException, IOException {
InputStream in = null;
if (!isXML) {
String[] cmd = getCommandLineArray(skipValidation);
Runtime runtime = Runtime.getRuntime();
try {
// Note: we can't use process.waitFor() here, because the result of
// 'process.getInputStream()' is passed around and manipulated by
// the parser. In order for .waitFor() to work, the stream needs to
// be taken care of immediately so that the process can return. Currently,
// with the process' input stream getting passed around, the call to
// .waitFor() creates a deadlock condition.
process = runtime.exec(cmd);
}
catch (IOException e) {
if (e.getMessage().endsWith("14001")) {//missing runtime dlls, probably
throw new PdbException("Missing runtime libraries. " + "Please refer to " +
README_FILENAME + " and follow instructions.");
}
throw e;
}
in = process.getInputStream();
InputStream err = process.getErrorStream();
thread = new PdbErrorReaderThread(err);
thread.start();
}
else {
in = new FileInputStream(pdbFile);
}
errHandler = new PdbErrorHandler();
try {
parser = XmlPullParserFactory.create(in, pdbFile.getName(), errHandler, false);
}
catch (SAXException e) {
throw new IOException(e.getMessage());
}
verifyPdbSignature(in);
}
/**
* Check to see if GUID and age in XML file matches GUID/Signature and age of binary
*
* @param in InputStream for XML file
* @throws IOException If an I/O error occurs
* @throws PdbException If error parsing the PDB.XML data
*/
private void verifyPdbSignature(InputStream in) throws IOException, PdbException {
XmlElement xmlelem;
try {
xmlelem = parser.peek();
}
catch (Exception e) {
if (!isXML) {
if (hasErrors()) {
throw new PdbException(getErrorAndWarningMessages());
}
throw new PdbException("PDB Execution failure of " + PDB_EXE + ".\n" +
"This was likely caused by severe execution failure which can occur if executed\n" +
"on an unsupported platform. It may be neccessary to rebuild the PDB executable\n" +
"for your platform (see Ghidra/Features/PDB/src).");
}
throw new PdbException("PDB parsing problem: " + e.getMessage());
}
if (!"pdb".equals(xmlelem.getName())) {
throw new PdbException("Unexpected PDB XML element: " + xmlelem.getName());
}
String xmlGuid = xmlelem.getAttribute("guid");
String xmlAge = xmlelem.getAttribute("age");
String warning = "";
String pdbGuid = programAttributes.getPdbGuid();
if (pdbGuid == null) {
String pdbSignature = programAttributes.getPdbSignature();
if (pdbSignature != null) {
pdbGuid = reformatSignatureToGuidForm(pdbSignature);
}
}
String pdbAge = programAttributes.getPdbAge();
if ((xmlGuid == null) || (pdbGuid == null)) {
if (xmlGuid == null) {
warning += "No GUID was listed in the XML file.";
}
if (pdbGuid == null) {
warning += " Could not find a PDB GUID for the binary.";
}
warning += " Could not complete verification of matching PDB signatures.";
}
else {
// Reformat PDB GUID so that it matches the way GUIDs are stored in XML
pdbGuid = pdbGuid.toUpperCase();
pdbGuid = "{" + pdbGuid + "}";
if (!xmlGuid.equals(pdbGuid)) {
warning = "PDB signature does not match.";
}
else {
// Also check that PDB ages match, if they are both available
if ((xmlAge != null) && (pdbAge != null)) {
int pdbAgeDecimal = Integer.parseInt(pdbAge, 16);
int xmlAgeDecimal = Integer.parseInt(xmlAge);
if (xmlAgeDecimal != pdbAgeDecimal) {
warning = "PDB ages do not match.";
}
}
}
}
if (warning.length() > 0) {
if (SystemUtilities.isInHeadlessMode()) {
throw new PdbException(warning + ".. Skipping PDB processing.");
}
int option = OptionDialog.showYesNoDialog(null, "Continue Loading PDB?",
warning + "\n " + "\nContinue anyway?" + "\n " +
"\nPlease note: Invalid disassembly may be produced!");
if (option != OptionDialog.OPTION_ONE) {
throw new PdbException(warning);
}
}
}
/**
* Translate signature to GUID form. A signature is usually 8 characters long. A GUID
* has 32 characters and its subparts are separated by '-' characters.
*
* @param pdbSignature signature for conversion
* @return reformatted String
*/
private String reformatSignatureToGuidForm(String pdbSignature) {
// GUID structure (32 total hex chars):
// {8 hex}-{4 hex}-{4 hex}-{4 hex}-{12 hex}
//
// If PDB signature is less than 32 chars, make up the rest in 0's.
// If > 32 chars (which it should never be), just truncate to 32 chars
if (pdbSignature.length() > 32) {
pdbSignature = pdbSignature.substring(0, 32);
}
StringBuilder builder = new StringBuilder(pdbSignature);
for (int i = pdbSignature.length(); i < 32; i++) {
builder = builder.append('0');
}
// Insert '-' characters at the right boundaries
builder = builder.insert(8, '-').insert(13, '-').insert(18, '-').insert(23, '-');
return builder.toString();
}
/**
* Checks if PDB has been loaded in the program
*
* @return whether PDB has been loaded or not
*/
public boolean isPdbLoaded() {
return programAttributes.isPdbLoaded();
}
// TODO: verify this method is necessary
private void cleanup() {
if (process != null) {
process.destroy();
process = null;
}
if (parser != null) {
parser.dispose();
parser = null;
}
//errHandler = null;
//thread = null;
if (dataTypeParser != null) {
dataTypeParser.clear();
}
}
boolean isCorrectKind(DataType dt, PdbKind kind) {
if (kind == PdbKind.STRUCTURE) {
return (dt instanceof Structure);
}
else if (kind == PdbKind.UNION) {
return (dt instanceof Union);
}
return false;
}
Composite createComposite(PdbKind kind, String name) {
if (kind == PdbKind.STRUCTURE) {
return createStructure(name, 0);
}
else if (kind == PdbKind.UNION) {
return createUnion(name);
}
throw new IllegalArgumentException("unsupported kind: " + kind);
}
Structure createStructure(String name, int length) {
SymbolPath path = new SymbolPath(name);
return new StructureDataType(getCategory(path.getParent(), true), path.getName(), length,
dataMgr);
}
Union createUnion(String name) {
SymbolPath path = new SymbolPath(name);
return new UnionDataType(getCategory(path.getParent(), true), path.getName(), dataMgr);
}
TypedefDataType createTypeDef(String name, DataType baseDataType) {
SymbolPath path = new SymbolPath(name);
return new TypedefDataType(getCategory(path.getParent(), true), path.getName(),
baseDataType, dataMgr);
}
EnumDataType createEnum(String name, int length) {
SymbolPath path = new SymbolPath(name);
return new EnumDataType(getCategory(path.getParent(), true), path.getName(), length,
dataMgr);
}
void createString(boolean isUnicode, Address address, MessageLog log) {
DataType dataType = isUnicode ? new UnicodeDataType() : new StringDataType();
createData(address, dataType, log);
}
void createData(Address address, String datatype, MessageLog log) throws CancelledException {
WrappedDataType wrappedDt = getDataTypeParser().findDataType(datatype);
if (wrappedDt == null) {
log.appendMsg("Error: Failed to resolve datatype " + datatype + " at " + address);
}
else if (wrappedDt.isZeroLengthArray()) {
Msg.debug(this, "Did not apply zero length array data " + datatype + " at " + address);
}
else {
createData(address, wrappedDt.getDataType(), log);
}
}
void createData(Address address, DataType dataType, MessageLog log) {
DumbMemBufferImpl memBuffer = new DumbMemBufferImpl(program.getMemory(), address);
DataTypeInstance dti = DataTypeInstance.getDataTypeInstance(dataType, memBuffer);
if (dti == null) {
log.appendMsg(
"Error: Failed to apply datatype " + dataType.getName() + " at " + address);
}
else {
createData(address, dti.getDataType(), dti.getLength(), log);
}
}
private void createData(Address address, DataType dataType, int dataTypeLength,
MessageLog log) {
// Ensure that we do not clear previously established code and data
Data existingData = null;
CodeUnit cu = program.getListing().getCodeUnitContaining(address);
if (cu != null) {
if ((cu instanceof Instruction) || !address.equals(cu.getAddress())) {
log.appendMsg("Warning: Did not create data type \"" + dataType.getDisplayName() +
"\" at address " + address + " due to conflict");
return;
}
Data d = (Data) cu;
if (d.isDefined()) {
existingData = d;
}
}
if (dataType == null) {
return;
}
if (dataType.getLength() <= 0 && dataTypeLength <= 0) {
log.appendMsg("Unknown dataTypeLength specified at address " + address + " for " +
dataType.getName());
return;
}
// TODO: This is really bad logic and should be refactored
// All conflicting data, not just the one containing address,
// needs to be considered and not blindly cleared.
if (existingData != null) {
DataType existingDataType = existingData.getDataType();
if (isEquivalent(existingData, existingData.getLength(), dataType)) {
return;
}
if (isEquivalent2(existingDataType, dataType)) {
return;
}
if (existingDataType.isEquivalent(dataType)) {
return;
}
}
Listing listing = program.getListing();
if (existingData == null) {
try {
listing.clearCodeUnits(address, address.add(dataTypeLength - 1), false);
if (dataType.getLength() == -1) {
listing.createData(address, dataType, dataTypeLength);
}
else {
listing.createData(address, dataType);
}
}
catch (Exception e) {
log.appendMsg("Unable to create " + dataType.getDisplayName() + " at 0x" + address +
": " + e.getMessage());
}
}
else if (isDataReplaceable(existingData)) {
try {
listing.clearCodeUnits(address, address.add(dataTypeLength - 1), false);
listing.createData(address, dataType, dataTypeLength);
}
catch (Exception e) {
log.appendMsg("Unable to replace " + dataType.getDisplayName() + " at 0x" +
address + ": " + e.getMessage());
}
}
else {
DataType existingDataType = existingData.getDataType();
String existingDataTypeString =
existingDataType == null ? "null" : existingDataType.getDisplayName();
log.appendMsg("Warning: Did not create data type \"" + dataType.getDisplayName() +
"\" at address " + address + ". Preferring existing datatype \"" +
existingDataTypeString + "\"");
}
}
private boolean isDataReplaceable(Data data) {
DataType dataType = data.getDataType();
if (dataType instanceof Pointer) {
Pointer pointer = (Pointer) dataType;
DataType pointerDataType = pointer.getDataType();
if (pointerDataType == null || pointerDataType.isEquivalent(DataType.DEFAULT)) {
return true;
}
}
else if (dataType instanceof Array) {
Array array = (Array) dataType;
DataType arrayDataType = array.getDataType();
if (arrayDataType == null || arrayDataType.isEquivalent(DataType.DEFAULT)) {
return true;
}
}
// All forms of Undefined data are replaceable
// TODO: maybe it should check the length of the data type before putting it down.
if (Undefined.isUndefined(dataType)) {
return true;
}
return false;
}
private boolean isEquivalent(Data existingData, int existingDataTypeLength,
DataType newDataType) {
if (existingData.hasStringValue()) {
if (newDataType instanceof ArrayDataType) {
Array array = (Array) newDataType;
DataType arrayDataType = array.getDataType();
if (arrayDataType instanceof ArrayStringable) {
if (array.getLength() == existingDataTypeLength) {
return true;
}
}
}
}
return false;
}
/**
* "char[12] *" "char * *"
*
* "ioinfo * *" "ioinfo[64] *"
*/
private boolean isEquivalent2(DataType datatype1, DataType datatype2) {
if (datatype1 == datatype2) {
return true;
}
if (datatype1 == null || datatype2 == null) {
return false;
}
if (datatype1 instanceof Array) {
Array array1 = (Array) datatype1;
if (datatype2 instanceof Array) {
Array array2 = (Array) datatype2;
return isEquivalent2(array1.getDataType(), array2.getDataType());
}
}
else if (datatype1 instanceof Pointer) {
Pointer pointer1 = (Pointer) datatype1;
if (datatype2 instanceof Array) {
Array array2 = (Array) datatype2;
return isEquivalent2(pointer1.getDataType(), array2.getDataType());
}
}
return datatype1.isEquivalent(datatype2);
}
boolean createSymbol(Address address, String symbolPathString, boolean forcePrimary,
MessageLog log) {
try {
Namespace namespace = program.getGlobalNamespace();
SymbolPath symbolPath = new SymbolPath(symbolPathString);
symbolPath = symbolPath.replaceInvalidChars();
String name = symbolPath.getName();
String namespacePath = symbolPath.getParentPath();
if (namespacePath != null) {
namespace = NamespaceUtils.createNamespaceHierarchy(namespacePath, namespace,
program, address, SourceType.IMPORTED);
}
Symbol s = SymbolUtilities.createPreferredLabelOrFunctionSymbol(program, address,
namespace, name, SourceType.IMPORTED);
if (s != null && forcePrimary) {
// PDB contains both mangled, namespace names, and global names
// If mangled name does not remain primary it will not get demamgled
// and we may not get signature information applied
SetLabelPrimaryCmd cmd =
new SetLabelPrimaryCmd(address, s.getName(), s.getParentNamespace());
cmd.applyTo(program);
}
return true;
}
catch (InvalidInputException e) {
log.appendMsg("Unable to create symbol: " + e.getMessage());
}
return false;
}
// DataType createPointer(DataType dt) {
// return PointerDataType.getPointer(dt, program.getDataTypeManager());
// }
// DataType getCachedDataType(String key) {
// return dataTypeCache.get(key);
// }
//
// void cacheDataType(String key, DataType dataType) {
// dataTypeCache.put(key, dataType);
// }
/**
* Get the PDB root category path
* @return PDB root category path
*/
CategoryPath getCategory() {
return pdbCategory;
}
/**
* Get the name with any namespace stripped
* @param name name with optional namespace prefix
* @return name without namespace prefix
*/
String stripNamespace(String name) {
int index = name.lastIndexOf(Namespace.NAMESPACE_DELIMITER);
if (index <= 0) {
return name;
}
return name.substring(index + Namespace.NAMESPACE_DELIMITER.length());
}
/**
* Get the category path associated with the namespace qualified data type name
* @param namespaceQualifiedDataTypeName data type name
* @param addPdbRoot true if PDB root category should be used, otherwise it will be omitted
* @return the category path
*/
CategoryPath getCategory(String namespaceQualifiedDataTypeName, boolean addPdbRoot) {
String[] names = namespaceQualifiedDataTypeName.split(Namespace.NAMESPACE_DELIMITER);
CategoryPath category = addPdbRoot ? pdbCategory : CategoryPath.ROOT;
if (names.length > 1) {
String[] categoryNames = new String[names.length - 1];
System.arraycopy(names, 0, categoryNames, 0, categoryNames.length);
for (String c : categoryNames) {
category = new CategoryPath(category, c);
}
}
return category;
}
/**
* Get the {@link CategoryPath} associated with the namespace specified by the
* {@link SymbolPath}, rooting it either at the Category Path root or the PDB Category.
* @param symbolPath the {@link SymbolPath} input; can be null if no depth in path.
* @param addPdbRoot True if PDB root category should be used, otherwise it will be omitted.
* @return {@link CategoryPath} created for the input.
*/
CategoryPath getCategory(SymbolPath symbolPath, boolean addPdbRoot) {
CategoryPath category = addPdbRoot ? pdbCategory : CategoryPath.ROOT;
if (symbolPath != null) {
List<String> names = symbolPath.asList();
for (String name : names) {
category = new CategoryPath(category, name);
}
}
return category;
}
/********************************************************************/
/* STATIC METHODS */
/********************************************************************/
/**
* Get the object that stores PDB-related attributes for the program.
*
* @param program program for which to find a matching PDB
* @return PDBProgramAttributes object associated with the program
*/
public static PdbProgramAttributes getPdbAttributes(Program program) {
return new PdbProgramAttributes(program);
}
/**
* Find the PDB associated with the given program using its attributes
*
* @param program program for which to find a matching PDB
* @return matching PDB for program, or null
* @throws PdbException if there was a problem with the PDB attributes
*/
public static File findPDB(Program program) throws PdbException {
return findPDB(getPdbAttributes(program), false, null, null);
}
/**
* Determine if the PDB has previously been loaded for the specified program.
* @param program program for which to find a matching PDB
* @return true if PDB has already been loaded
*/
public static boolean isAlreadyLoaded(Program program) {
return getPdbAttributes(program).isPdbLoaded();
}
/**
* Find the PDB associated with the given program using its attributes, specifying the
* location where symbols are stored.
*
* @param program program for which to find a matching PDB
* @param includePeSpecifiedPdbPath to also check the PE-header-specified PDB path
* @param symbolsRepositoryPath location where downloaded symbols are stored
* @return matching PDB for program, or null
* @throws PdbException if there was a problem with the PDB attributes
*/
public static File findPDB(Program program, boolean includePeSpecifiedPdbPath,
String symbolsRepositoryPath) throws PdbException {
return findPDB(getPdbAttributes(program), includePeSpecifiedPdbPath, symbolsRepositoryPath,
null);
}
/**
* Find a matching PDB file using attributes associated with the program. User can specify the
* type of file to search from (.pdb or .pdb.xml).
*
* @param pdbAttributes PDB attributes associated with the program
* @param includePeSpecifiedPdbPath to also check the PE-header-specified PDB path
* @param symbolsRepositoryPath location of the local symbols repository (can be null)
* @param fileType type of file to search for (can be null)
* @return matching PDB file (or null, if not found)
* @throws PdbException if there was a problem with the PDB attributes
*/
public static File findPDB(PdbProgramAttributes pdbAttributes,
boolean includePeSpecifiedPdbPath, String symbolsRepositoryPath, PdbFileType fileType)
throws PdbException {
// Store potential names of PDB files and potential locations of those files,
// so that all possible combinations can be searched.
// LinkedHashSet is used when we need to preserve order
Set<String> guidSubdirPaths = new HashSet<>();
String guidAgeString = pdbAttributes.getGuidAgeCombo();
if (guidAgeString == null) {
throw new PdbException(
"Incomplete PDB information (GUID/Signature and/or age) associated with this program.\n" +
"Either the program is not a PE, or it was not compiled with debug information.");
}
List<String> potentialPdbNames = pdbAttributes.getPotentialPdbFilenames();
for (String potentialName : potentialPdbNames) {
guidSubdirPaths.add(File.separator + potentialName + File.separator + guidAgeString);
}
return checkPathsForPdb(symbolsRepositoryPath, guidSubdirPaths, potentialPdbNames, fileType,
pdbAttributes, includePeSpecifiedPdbPath);
}
/**
* Check potential paths in a specific order. If the symbolsRepositoryPath parameter is
* supplied and the directory exists, that directory will be searched first for the
* matching PDB file.
*
* If the file type is supplied, then only that file type will be searched for. Otherwise,
* the search process depends on the current operating system that Ghidra is running from:
*
* - Windows: look in the symbolsRepositoryPath for a matching .pdb file. If one does not
* exist, look for a .pdb.xml file in symbolsRepositoryPath. If not found, then
* search for a matching .pdb file, then .pdb.xml file, in other directories.
* - non-Windows: look in the symbolsRepositoryPath for a matching .pdb.xml file. If one does
* not exist, look for a .pdb file. If a .pdb file is found, return an error saying
* that it was found, but could not be processed. If no matches found in
* symbolsRepositoryPath, then look for .pdb.xml file, then .pdb.xml file in other
* directories.
*
* @param symbolsRepositoryPath location of the local symbols repository (can be null)
* @param guidSubdirPaths subdirectory paths (that include the PDB's GUID) that may contain
* a matching PDB
* @param potentialPdbNames all potential filenames for the PDB file(s) that match the program
* @param fileType file type to search for (can be null)
* @param pdbAttributes PDB attributes associated with the program
* @return matching PDB file, if found (else null)
*/
private static File checkPathsForPdb(String symbolsRepositoryPath, Set<String> guidSubdirPaths,
List<String> potentialPdbNames, PdbFileType fileType,
PdbProgramAttributes pdbAttributes, boolean includePeSpecifiedPdbPath) {
File foundPdb = null;
Set<File> symbolsRepoPaths =
getSymbolsRepositoryPaths(symbolsRepositoryPath, guidSubdirPaths);
Set<File> predefinedPaths =
getPredefinedPaths(guidSubdirPaths, pdbAttributes, includePeSpecifiedPdbPath);
boolean fileTypeSpecified = (fileType != null), checkForXml;
// If the file type is specified, look for that type of file only.
if (fileTypeSpecified) {
checkForXml = (fileType == PdbFileType.XML) ? true : false;
foundPdb = checkForPDBorXML(symbolsRepoPaths, potentialPdbNames, checkForXml);
if (foundPdb != null) {
return foundPdb;
}
foundPdb = checkForPDBorXML(predefinedPaths, potentialPdbNames, checkForXml);
return foundPdb;
}
// If the file type is not specified, look for both file types, starting with the
// file type that's most appropriate for the Operating System (PDB for Windows, XML for
// non-Windows).
checkForXml = onWindows ? false : true;
// Start by searching in symbolsRepositoryPath, if available.
if (symbolsRepositoryPath != null) {
foundPdb = checkSpecificPathsForPdb(symbolsRepoPaths, potentialPdbNames, checkForXml);
}
if (foundPdb != null) {
return foundPdb;
}
return checkSpecificPathsForPdb(predefinedPaths, potentialPdbNames, checkForXml);
}
private static File checkSpecificPathsForPdb(Set<File> paths, List<String> potentialPdbNames,
boolean checkForXmlFirst) {
File foundPdb = checkForPDBorXML(paths, potentialPdbNames, checkForXmlFirst);
if (foundPdb != null) {
return foundPdb;
}
foundPdb = checkForPDBorXML(paths, potentialPdbNames, !checkForXmlFirst);
return foundPdb;
}
private static Set<File> getSymbolsRepositoryPaths(String symbolsRepositoryPath,
Set<String> guidSubdirPaths) {
Set<File> symbolsRepoPaths = new LinkedHashSet<>();
// Collect sub-directories of the symbol repository that exist
File symRepoFile;
if (symbolsRepositoryPath != null &&
(symRepoFile = new File(symbolsRepositoryPath)).isDirectory()) {
for (String guidSubdir : guidSubdirPaths) {
File testDir = new File(symRepoFile, guidSubdir);
if (testDir.isDirectory()) {
symbolsRepoPaths.add(testDir);
}
}
// Check outer folder last
symbolsRepoPaths.add(symRepoFile);
}
return symbolsRepoPaths;
}
// Get list of "paths we know about" to search for PDBs
private static Set<File> getPredefinedPaths(Set<String> guidSubdirPaths,
PdbProgramAttributes pdbAttributes, boolean includePeSpecifiedPdbPath) {
Set<File> predefinedPaths = new LinkedHashSet<>();
getPathsFromAttributes(pdbAttributes, includePeSpecifiedPdbPath, predefinedPaths);
getWindowsPaths(guidSubdirPaths, predefinedPaths);
getLibraryPaths(guidSubdirPaths, predefinedPaths);
return predefinedPaths;
}
private static void getLibraryPaths(Set<String> guidSubdirPaths, Set<File> predefinedPaths) {
String[] libraryPaths = LibrarySearchPathManager.getLibraryPaths();
File libFile, subDir;
for (String path : libraryPaths) {
if ((libFile = new File(path)).isDirectory()) {
predefinedPaths.add(libFile);
// Check alternate locations
for (String guidSubdir : guidSubdirPaths) {
if ((subDir = new File(path, guidSubdir)).isDirectory()) {
predefinedPaths.add(subDir);
}
}
}
}
}
private static void getWindowsPaths(Set<String> guidSubdirPaths, Set<File> predefinedPaths) {
// Don't have to call .exists(), since .isDirectory() does that already
if (onWindows && SPECIAL_PDB_LOCATION.isDirectory()) {
predefinedPaths.add(SPECIAL_PDB_LOCATION);
// Check alternate locations
String specialPdbPath = SPECIAL_PDB_LOCATION.getAbsolutePath();
for (String guidSubdir : guidSubdirPaths) {
File testDir = new File(specialPdbPath + guidSubdir);
if (testDir.isDirectory()) {
predefinedPaths.add(testDir);
}
}
}
}
private static void getPathsFromAttributes(PdbProgramAttributes pdbAttributes,
boolean includePeSpecifiedPdbPath, Set<File> predefinedPaths) {
if (pdbAttributes != null) {
String currentPath = pdbAttributes.getPdbFile();
if (currentPath != null && includePeSpecifiedPdbPath) {
File parentDir = new File(currentPath).getParentFile();
if (parentDir != null && parentDir.exists()) {
predefinedPaths.add(parentDir);
}
}
currentPath = pdbAttributes.getExecutablePath();
if (currentPath != null && !currentPath.equals("unknown")) {
File parentDir = new File(currentPath).getParentFile();
if (parentDir != null && parentDir.exists()) {
predefinedPaths.add(parentDir);
}
}
}
}
/**
* Returns the first PDB-type file found. Assumes list of potentialPdbDirs is in the order
* in which the directories should be searched.
*
* @param potentialPdbDirs potential PDB directories
* @param potentialPdbNames potential PDB names
* @param findXML - if true, only searches for the .pdb.xml version of the .pdb file
* @return the first file found
*/
private static File checkForPDBorXML(Set<File> potentialPdbDirs, List<String> potentialPdbNames,
boolean findXML) {
File pdb;
for (File pdbPath : potentialPdbDirs) {
for (String filename : potentialPdbNames) {
if (findXML) {
pdb = new File(pdbPath, filename + PdbFileType.XML.toString());
}
else {
pdb = new File(pdbPath, filename);
}
// Note: isFile() also checks for existence
if (pdb.isFile()) {
return pdb;
}
}
}
return null;
}
PdbDataTypeParser getDataTypeParser() {
if (program == null) {
throw new AssertException("Parser was not constructed with program");
}
if (dataTypeParser == null) {
dataTypeParser = new PdbDataTypeParser(program.getDataTypeManager(), service, monitor);
}
return dataTypeParser;
}
void cacheDataType(String name, DataType dataType) {
getDataTypeParser().cacheDataType(name, dataType);
}
DataType getCachedDataType(String name) {
return getDataTypeParser().getCachedDataType(name);
}
void addDataType(DataType dataType) {
getDataTypeParser().addDataType(dataType);
}
WrappedDataType findDataType(String dataTypeName) throws CancelledException {
return getDataTypeParser().findDataType(dataTypeName);
}
public PdbMember getPdbXmlMember(XmlTreeNode node) {
return new PdbXmlMember(node);
}
public PdbXmlMember getPdbXmlMember(XmlElement element) {
return new PdbXmlMember(element);
}
class PdbXmlMember extends DefaultPdbMember {
PdbXmlMember(XmlTreeNode node) {
this(node.getStartElement());
}
PdbXmlMember(XmlElement element) {
super(SymbolUtilities.replaceInvalidChars(element.getAttribute("name"), false),
element.getAttribute("datatype"),
XmlUtilities.parseInt(element.getAttribute("offset")),
PdbKind.parse(element.getAttribute("kind")), getDataTypeParser());
}
}
}
| GT-3029 Fix PDB validation logic | Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb/PdbParser.java | GT-3029 Fix PDB validation logic | <ide><path>hidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb/PdbParser.java
<ide> }
<ide> }
<ide> }
<add> else { // only for .pdb.xml files.
<add> verifyPdbSignature();
<add> }
<ide> parsed = true;
<ide> }
<ide>
<ide> catch (SAXException e) {
<ide> throw new IOException(e.getMessage());
<ide> }
<del>
<del> verifyPdbSignature(in);
<ide> }
<ide>
<ide> /**
<ide> * Check to see if GUID and age in XML file matches GUID/Signature and age of binary
<ide> *
<del> * @param in InputStream for XML file
<ide> * @throws IOException If an I/O error occurs
<ide> * @throws PdbException If error parsing the PDB.XML data
<ide> */
<del> private void verifyPdbSignature(InputStream in) throws IOException, PdbException {
<add> private void verifyPdbSignature() throws IOException, PdbException {
<ide>
<ide> XmlElement xmlelem;
<ide> |
|
Java | apache-2.0 | 3445e3452e67d40dda99624a5a5ba80e4d26b7bb | 0 | damencho/jitsi,bhatvv/jitsi,jitsi/jitsi,jibaro/jitsi,jitsi/jitsi,HelioGuilherme66/jitsi,Metaswitch/jitsi,gpolitis/jitsi,tuijldert/jitsi,level7systems/jitsi,tuijldert/jitsi,procandi/jitsi,Metaswitch/jitsi,procandi/jitsi,ibauersachs/jitsi,ibauersachs/jitsi,damencho/jitsi,laborautonomo/jitsi,martin7890/jitsi,jibaro/jitsi,bhatvv/jitsi,bebo/jitsi,gpolitis/jitsi,tuijldert/jitsi,pplatek/jitsi,bebo/jitsi,jitsi/jitsi,martin7890/jitsi,dkcreinoso/jitsi,dkcreinoso/jitsi,iant-gmbh/jitsi,damencho/jitsi,cobratbq/jitsi,iant-gmbh/jitsi,laborautonomo/jitsi,HelioGuilherme66/jitsi,level7systems/jitsi,iant-gmbh/jitsi,HelioGuilherme66/jitsi,bhatvv/jitsi,ringdna/jitsi,laborautonomo/jitsi,procandi/jitsi,ibauersachs/jitsi,jibaro/jitsi,gpolitis/jitsi,gpolitis/jitsi,bebo/jitsi,jitsi/jitsi,459below/jitsi,damencho/jitsi,mckayclarey/jitsi,marclaporte/jitsi,459below/jitsi,laborautonomo/jitsi,level7systems/jitsi,iant-gmbh/jitsi,jitsi/jitsi,jibaro/jitsi,ringdna/jitsi,mckayclarey/jitsi,martin7890/jitsi,marclaporte/jitsi,pplatek/jitsi,tuijldert/jitsi,iant-gmbh/jitsi,laborautonomo/jitsi,procandi/jitsi,ringdna/jitsi,cobratbq/jitsi,level7systems/jitsi,ringdna/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,pplatek/jitsi,pplatek/jitsi,cobratbq/jitsi,level7systems/jitsi,Metaswitch/jitsi,mckayclarey/jitsi,mckayclarey/jitsi,459below/jitsi,martin7890/jitsi,mckayclarey/jitsi,bebo/jitsi,dkcreinoso/jitsi,bhatvv/jitsi,marclaporte/jitsi,pplatek/jitsi,procandi/jitsi,459below/jitsi,gpolitis/jitsi,marclaporte/jitsi,jibaro/jitsi,dkcreinoso/jitsi,cobratbq/jitsi,459below/jitsi,martin7890/jitsi,damencho/jitsi,HelioGuilherme66/jitsi,tuijldert/jitsi,ibauersachs/jitsi,Metaswitch/jitsi,marclaporte/jitsi,dkcreinoso/jitsi,ibauersachs/jitsi,bhatvv/jitsi,ringdna/jitsi,bebo/jitsi | /*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.contactlist;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.customcontrols.*;
import net.java.sip.communicator.impl.gui.i18n.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.protocol.*;
/**
* The <tt>ContactListCellRenderer</tt> is the custom cell renderer used in the
* SIP-Communicator's <tt>ContactList</tt>. It extends JPanel instead of JLabel,
* which allows adding different buttons and icons to the contact cell.
* The cell border and background are repainted.
*
* @author Yana Stamcheva
*/
public class ContactListCellRenderer extends JPanel
implements ListCellRenderer {
private JLabel nameLabel = new JLabel();
private JPanel buttonsPanel;
private SIPCommButton extendPanelButton = new SIPCommButton(ImageLoader
.getImage(ImageLoader.MORE_INFO_ICON), ImageLoader
.getImage(ImageLoader.MORE_INFO_ICON));
private boolean isSelected = false;
private boolean isLeaf = true;
private MainFrame mainFrame;
private int CONTACT_PROTOCOL_BUTTON_WIDTH = 20;
/**
* Initialize the panel containing the node.
*/
public ContactListCellRenderer(MainFrame mainFrame) {
super(new BorderLayout());
this.mainFrame = mainFrame;
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new GridLayout(1, 0));
this.buttonsPanel.setName("buttonsPanel");
this.setOpaque(false);
this.nameLabel.setOpaque(false);
this.buttonsPanel.setOpaque(false);
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
this.nameLabel.setIconTextGap(2);
this.nameLabel.setPreferredSize(new Dimension(10, 17));
this.add(nameLabel, BorderLayout.CENTER);
}
/**
* Implements the <tt>ListCellRenderer</tt> method.
*
* Returns this panel that has been configured to display the meta contact
* and meta contact group cells.
*/
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
ContactList contactList = (ContactList) list;
ContactListModel listModel = (ContactListModel) contactList.getModel();
String toolTipText = "<html>";
if (value instanceof MetaContact) {
MetaContact contactItem = (MetaContact) value;
String displayName = contactItem.getDisplayName();
if (displayName == null || displayName.length() < 1)
{
displayName = Messages.getI18NString("unknown").getText();
}
toolTipText += "<b>"+displayName+"</b>";
this.nameLabel.setText(displayName);
this.nameLabel.setIcon(listModel
.getMetaContactStatusIcon(contactItem));
this.nameLabel.setFont(this.getFont().deriveFont(Font.PLAIN));
this.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
// We should set the bounds of the cell explicitely in order to
// make getComponentAt work properly.
this.setBounds(0, 0, list.getWidth() - 2, 17);
this.buttonsPanel.removeAll();
Iterator i = contactItem.getContacts();
int buttonsPanelWidth = 0;
while (i.hasNext()) {
Contact protocolContact = (Contact) i.next();
Image protocolStatusIcon
= ImageLoader.getBytesInImage(
protocolContact.getPresenceStatus().getStatusIcon());
int providerIndex = mainFrame.getProviderIndex(
protocolContact.getProtocolProvider());
Image img;
if(providerIndex > 0) {
img = createIndexedImage(protocolStatusIcon, providerIndex);
}
else {
img = protocolStatusIcon;
}
ContactProtocolButton contactProtocolButton
= new ContactProtocolButton(img);
contactProtocolButton.setProtocolContact(protocolContact);
contactProtocolButton.setBounds(buttonsPanelWidth,
16,
CONTACT_PROTOCOL_BUTTON_WIDTH,//the width is fixed in
//order all the icons to be with the same size
img.getHeight(null));
buttonsPanelWidth += CONTACT_PROTOCOL_BUTTON_WIDTH;
this.buttonsPanel.add(contactProtocolButton);
String contactDisplayName = protocolContact.getDisplayName();
String contactAddress = protocolContact.getAddress();
String statusMessage = protocolContact.getStatusMessage();
toolTipText
+= "<br>"
+ ((!contactDisplayName
.equals(contactAddress))
? contactDisplayName + " ("+contactAddress + ")"
: contactDisplayName)
+ ((statusMessage != null && statusMessage.length() > 0)
? " - " + statusMessage : "");
}
this.buttonsPanel.setPreferredSize(
new Dimension(buttonsPanelWidth, 16));
this.buttonsPanel.setBounds(
list.getWidth() - 2 - buttonsPanelWidth, 0,
buttonsPanelWidth, 16);
this.nameLabel.setBounds(
0, 0, list.getWidth() - 2 - buttonsPanelWidth, 17);
this.isLeaf = true;
} else if (value instanceof MetaContactGroup) {
MetaContactGroup groupItem = (MetaContactGroup) value;
toolTipText += groupItem.getGroupName();
this.nameLabel.setText(groupItem.getGroupName()
+ " ( " + groupItem.countChildContacts() + " )");
this.nameLabel.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.GROUPS_16x16_ICON)));
this.nameLabel.setFont(this.getFont().deriveFont(Font.BOLD));
this.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
// We should set the bounds of the cell explicitely in order to
// make getComponentAt work properly.
this.setBounds(0, 0, list.getWidth() - 2, 20);
//this.remove(buttonsPanel);
this.buttonsPanel.removeAll();
JLabel groupContentIndicator = new JLabel();
if(((ContactListModel)list.getModel()).isGroupClosed(groupItem))
groupContentIndicator.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.CLOSED_GROUP)));
else
groupContentIndicator.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.OPENED_GROUP)));
//the width is fixed in
//order all the icons to be with the same size
groupContentIndicator.setBounds(0, 0, 12, 12);
this.buttonsPanel.setPreferredSize(
new Dimension(17, 16));
this.buttonsPanel.setBounds(
list.getWidth() - 2 - 17, 0,
17, 16);
this.buttonsPanel.add(groupContentIndicator);
this.isLeaf = false;
}
this.add(buttonsPanel, BorderLayout.EAST);
toolTipText += "</html>";
this.setToolTipText(toolTipText);
this.isSelected = isSelected;
return this;
}
/**
* Adds the protocol provider index to the given source image.
* @param sourceImage
* @param index
* @return
*/
private Image createIndexedImage(Image sourceImage, int index)
{
BufferedImage buffImage = new BufferedImage(
22, 16, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D)buffImage.getGraphics();
AlphaComposite ac =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
AntialiasingManager.activateAntialiasing(g);
g.setColor(Color.DARK_GRAY);
g.setFont(Constants.FONT.deriveFont(Font.BOLD, 9));
g.drawImage(sourceImage, 0, 0, null);
g.setComposite(ac);
g.drawString(new Integer(index+1).toString(), 14, 8);
return buffImage;
}
/**
* Paint a background for all groups and a round blue border and background
* when a cell is selected.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
AntialiasingManager.activateAntialiasing(g2);
if (!this.isLeaf) {
GradientPaint p = new GradientPaint(0, 0,
Constants.SELECTED_COLOR,
this.getWidth(),
this.getHeight(),
Constants.GRADIENT_LIGHT_COLOR);
g2.setPaint(p);
g2.fillRoundRect(1, 1, this.getWidth(), this.getHeight() - 1, 7, 7);
}
if (this.isSelected) {
g2.setColor(Constants.SELECTED_COLOR);
g2.fillRoundRect(1, 0, this.getWidth(), this.getHeight(), 7, 7);
g2.setColor(Constants.LIST_SELECTION_BORDER_COLOR);
g2.setStroke(new BasicStroke(1.5f));
g2.drawRoundRect(1, 0, this.getWidth() - 1, this.getHeight() - 1,
7, 7);
}
}
}
| src/net/java/sip/communicator/impl/gui/main/contactlist/ContactListCellRenderer.java | /*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.contactlist;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.customcontrols.*;
import net.java.sip.communicator.impl.gui.i18n.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.protocol.*;
/**
* The <tt>ContactListCellRenderer</tt> is the custom cell renderer used in the
* SIP-Communicator's <tt>ContactList</tt>. It extends JPanel instead of JLabel,
* which allows adding different buttons and icons to the contact cell.
* The cell border and background are repainted.
*
* @author Yana Stamcheva
*/
public class ContactListCellRenderer extends JPanel
implements ListCellRenderer {
private JLabel nameLabel = new JLabel();
private JPanel buttonsPanel;
private SIPCommButton extendPanelButton = new SIPCommButton(ImageLoader
.getImage(ImageLoader.MORE_INFO_ICON), ImageLoader
.getImage(ImageLoader.MORE_INFO_ICON));
private boolean isSelected = false;
private boolean isLeaf = true;
private MainFrame mainFrame;
private int CONTACT_PROTOCOL_BUTTON_WIDTH = 20;
/**
* Initialize the panel containing the node.
*/
public ContactListCellRenderer(MainFrame mainFrame) {
super(new BorderLayout());
this.mainFrame = mainFrame;
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new GridLayout(1, 0));
this.buttonsPanel.setName("buttonsPanel");
this.setOpaque(false);
this.nameLabel.setOpaque(false);
this.buttonsPanel.setOpaque(false);
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
this.nameLabel.setIconTextGap(2);
this.nameLabel.setPreferredSize(new Dimension(10, 17));
this.add(nameLabel, BorderLayout.CENTER);
}
/**
* Implements the <tt>ListCellRenderer</tt> method.
*
* Returns this panel that has been configured to display the meta contact
* and meta contact group cells.
*/
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
ContactList contactList = (ContactList) list;
ContactListModel listModel = (ContactListModel) contactList.getModel();
String toolTipText = "<html>";
if (value instanceof MetaContact) {
MetaContact contactItem = (MetaContact) value;
String displayName = contactItem.getDisplayName();
if (displayName == null || displayName.length() < 1)
{
displayName = Messages.getI18NString("unknown").getText();
}
toolTipText += "<b>"+displayName+"</b>";
this.nameLabel.setText(displayName);
this.nameLabel.setIcon(listModel
.getMetaContactStatusIcon(contactItem));
this.nameLabel.setFont(this.getFont().deriveFont(Font.PLAIN));
this.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
// We should set the bounds of the cell explicitely in order to
// make getComponentAt work properly.
this.setBounds(0, 0, list.getWidth() - 2, 17);
this.buttonsPanel.removeAll();
Iterator i = contactItem.getContacts();
int buttonsPanelWidth = 0;
while (i.hasNext()) {
Contact protocolContact = (Contact) i.next();
Image protocolStatusIcon
= ImageLoader.getBytesInImage(
protocolContact.getPresenceStatus().getStatusIcon());
int providerIndex = mainFrame.getProviderIndex(
protocolContact.getProtocolProvider());
Image img;
if(providerIndex > 0) {
img = createIndexedImage(protocolStatusIcon, providerIndex);
}
else {
img = protocolStatusIcon;
}
ContactProtocolButton contactProtocolButton
= new ContactProtocolButton(img);
contactProtocolButton.setProtocolContact(protocolContact);
contactProtocolButton.setBounds(buttonsPanelWidth,
16,
CONTACT_PROTOCOL_BUTTON_WIDTH,//the width is fixed in
//order all the icons to be with the same size
img.getHeight(null));
buttonsPanelWidth += CONTACT_PROTOCOL_BUTTON_WIDTH;
this.buttonsPanel.add(contactProtocolButton);
String contactDisplayName = protocolContact.getDisplayName();
String contactAddress = protocolContact.getAddress();
String statusMessage = protocolContact.getStatusMessage();
toolTipText
+= "<br>"
+ ((!contactDisplayName
.equals(contactAddress))
? contactDisplayName + " ("+contactAddress + ")"
: contactDisplayName)
+ ((statusMessage != null && statusMessage.length() > 0)
? " - " + statusMessage : "");
}
this.buttonsPanel.setPreferredSize(
new Dimension(buttonsPanelWidth, 16));
this.buttonsPanel.setBounds(
list.getWidth() - 2 - buttonsPanelWidth, 0,
buttonsPanelWidth, 16);
this.nameLabel.setBounds(
0, 0, list.getWidth() - 2 - buttonsPanelWidth, 17);
this.add(buttonsPanel, BorderLayout.EAST);
this.isLeaf = true;
} else if (value instanceof MetaContactGroup) {
MetaContactGroup groupItem = (MetaContactGroup) value;
toolTipText += groupItem.getGroupName();
this.nameLabel.setText(groupItem.getGroupName()
+ " ( " + groupItem.countChildContacts() + " )");
this.nameLabel.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.GROUPS_16x16_ICON)));
this.nameLabel.setFont(this.getFont().deriveFont(Font.BOLD));
this.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
// We should set the bounds of the cell explicitely in order to
// make getComponentAt work properly.
this.setBounds(0, 0, list.getWidth() - 2, 20);
//this.remove(buttonsPanel);
this.buttonsPanel.removeAll();
JLabel groupContentIndicator = new JLabel();
if(((ContactListModel)list.getModel()).isGroupClosed(groupItem))
groupContentIndicator.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.CLOSED_GROUP)));
else
groupContentIndicator.setIcon(new ImageIcon(ImageLoader
.getImage(ImageLoader.OPENED_GROUP)));
//the width is fixed in
//order all the icons to be with the same size
groupContentIndicator.setBounds(0, 0, 12, 12);
this.buttonsPanel.setPreferredSize(
new Dimension(17, 16));
this.buttonsPanel.setBounds(
list.getWidth() - 2 - 17, 0,
17, 16);
this.buttonsPanel.add(groupContentIndicator);
this.isLeaf = false;
}
toolTipText += "</html>";
this.setToolTipText(toolTipText);
this.isSelected = isSelected;
return this;
}
/**
* Adds the protocol provider index to the given source image.
* @param sourceImage
* @param index
* @return
*/
private Image createIndexedImage(Image sourceImage, int index)
{
BufferedImage buffImage = new BufferedImage(
22, 16, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D)buffImage.getGraphics();
AlphaComposite ac =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
AntialiasingManager.activateAntialiasing(g);
g.setColor(Color.DARK_GRAY);
g.setFont(Constants.FONT.deriveFont(Font.BOLD, 9));
g.drawImage(sourceImage, 0, 0, null);
g.setComposite(ac);
g.drawString(new Integer(index+1).toString(), 14, 8);
return buffImage;
}
/**
* Paint a background for all groups and a round blue border and background
* when a cell is selected.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
AntialiasingManager.activateAntialiasing(g2);
if (!this.isLeaf) {
GradientPaint p = new GradientPaint(0, 0,
Constants.SELECTED_COLOR,
this.getWidth(),
this.getHeight(),
Constants.GRADIENT_LIGHT_COLOR);
g2.setPaint(p);
g2.fillRoundRect(1, 1, this.getWidth(), this.getHeight() - 1, 7, 7);
}
if (this.isSelected) {
g2.setColor(Constants.SELECTED_COLOR);
g2.fillRoundRect(1, 0, this.getWidth(), this.getHeight(), 7, 7);
g2.setColor(Constants.LIST_SELECTION_BORDER_COLOR);
g2.setStroke(new BasicStroke(1.5f));
g2.drawRoundRect(1, 0, this.getWidth() - 1, this.getHeight() - 1,
7, 7);
}
}
}
| Fix close, open group icons in contact list.
| src/net/java/sip/communicator/impl/gui/main/contactlist/ContactListCellRenderer.java | Fix close, open group icons in contact list. | <ide><path>rc/net/java/sip/communicator/impl/gui/main/contactlist/ContactListCellRenderer.java
<ide> buttonsPanelWidth, 16);
<ide> this.nameLabel.setBounds(
<ide> 0, 0, list.getWidth() - 2 - buttonsPanelWidth, 17);
<del>
<del> this.add(buttonsPanel, BorderLayout.EAST);
<ide>
<ide> this.isLeaf = true;
<ide> } else if (value instanceof MetaContactGroup) {
<ide>
<ide> //this.remove(buttonsPanel);
<ide> this.buttonsPanel.removeAll();
<del>
<add>
<ide> JLabel groupContentIndicator = new JLabel();
<del>
<add>
<ide> if(((ContactListModel)list.getModel()).isGroupClosed(groupItem))
<ide> groupContentIndicator.setIcon(new ImageIcon(ImageLoader
<ide> .getImage(ImageLoader.CLOSED_GROUP)));
<ide> this.isLeaf = false;
<ide> }
<ide>
<add> this.add(buttonsPanel, BorderLayout.EAST);
<add>
<ide> toolTipText += "</html>";
<ide> this.setToolTipText(toolTipText);
<ide> |
|
Java | mit | cdb9e6a3112b993d6334fc85fa7778516f226356 | 0 | schmave/demschooltools,schmave/demschooltools,schmave/demschooltools,schmave/demschooltools,schmave/demschooltools | package models;
import java.io.*;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.persistence.*;
import com.avaje.ebean.Model;
import com.avaje.ebean.Model.Finder;
import com.fasterxml.jackson.annotation.*;
import controllers.Application;
import play.libs.Json;
@Entity
public class AttendanceDay extends Model {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "attendance_day_id_seq")
public Integer id;
public Date day;
@ManyToOne()
@JoinColumn(name="person_id")
public Person person;
public String code;
public Time start_time;
public Time end_time;
public static Finder<Integer, AttendanceDay> find = new Finder<>(
Integer.class, AttendanceDay.class
);
public static AttendanceDay create(Date day, Person p)
{
AttendanceDay result = new AttendanceDay();
result.person = p;
result.day = day;
result.save();
return result;
}
public static Time parseTime(String time_string) throws Exception {
if (time_string == null || time_string.equals("")) {
return null;
}
String[] formats = {"h:mm a", "h:mma"};
for (String format : formats) {
try {
Date d = new SimpleDateFormat(format).parse(time_string);
return new Time(d.getTime());
} catch (ParseException e) {
}
}
return null;
}
public void edit(String code, String start_time, String end_time) throws Exception {
if (code.equals("")) {
this.code = null;
} else {
this.code = code;
}
this.start_time = parseTime(start_time);
this.end_time = parseTime(end_time);
this.update();
}
@JsonIgnore
public double getHours() {
return (end_time.getTime() - start_time.getTime()) / (1000.0 * 60 * 60);
}
}
| app/models/AttendanceDay.java | package models;
import java.io.*;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.persistence.*;
import com.avaje.ebean.Model;
import com.avaje.ebean.Model.Finder;
import com.fasterxml.jackson.annotation.*;
import controllers.Application;
import play.libs.Json;
@Entity
public class AttendanceDay extends Model {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "attendance_day_id_seq")
public Integer id;
public Date day;
@ManyToOne()
@JoinColumn(name="person_id")
public Person person;
public String code;
public Time start_time;
public Time end_time;
public static Finder<Integer, AttendanceDay> find = new Finder<>(
Integer.class, AttendanceDay.class
);
public static AttendanceDay create(Date day, Person p)
{
AttendanceDay result = new AttendanceDay();
result.person = p;
result.day = day;
result.save();
return result;
}
public static Time parseTime(String time_string) throws Exception {
if (time_string == null || time_string.equals("")) {
return null;
}
Date d = new SimpleDateFormat("h:mm a").parse(time_string);
return new Time(d.getTime());
}
public void edit(String code, String start_time, String end_time) throws Exception {
if (code.equals("")) {
this.code = null;
} else {
this.code = code;
}
this.start_time = parseTime(start_time);
this.end_time = parseTime(end_time);
this.update();
}
@JsonIgnore
public double getHours() {
return (end_time.getTime() - start_time.getTime()) / (1000.0 * 60 * 60);
}
}
| Catch exception when time is unparseable; try multiple formats. Fixes #15
| app/models/AttendanceDay.java | Catch exception when time is unparseable; try multiple formats. Fixes #15 | <ide><path>pp/models/AttendanceDay.java
<ide>
<ide> import java.io.*;
<ide> import java.sql.Time;
<add>import java.text.ParseException;
<ide> import java.text.SimpleDateFormat;
<ide> import java.util.*;
<ide>
<ide> if (time_string == null || time_string.equals("")) {
<ide> return null;
<ide> }
<add>
<add> String[] formats = {"h:mm a", "h:mma"};
<ide>
<del> Date d = new SimpleDateFormat("h:mm a").parse(time_string);
<del> return new Time(d.getTime());
<add> for (String format : formats) {
<add> try {
<add> Date d = new SimpleDateFormat(format).parse(time_string);
<add> return new Time(d.getTime());
<add> } catch (ParseException e) {
<add> }
<add> }
<add>
<add> return null;
<ide> }
<ide>
<ide> public void edit(String code, String start_time, String end_time) throws Exception { |
|
Java | apache-2.0 | a894df51e47d70fa56749a245f12867e35b8c0e1 | 0 | idea4bsd/idea4bsd,jexp/idea2,da1z/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,da1z/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,FHannes/intellij-community,amith01994/intellij-community,adedayo/intellij-community,amith01994/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,signed/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,izonder/intellij-community,izonder/intellij-community,xfournet/intellij-community,robovm/robovm-studio,slisson/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,vladmm/intellij-community,joewalnes/idea-community,apixandru/intellij-community,FHannes/intellij-community,hurricup/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,supersven/intellij-community,retomerz/intellij-community,kdwink/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,jexp/idea2,ol-loginov/intellij-community,amith01994/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,kool79/intellij-community,fitermay/intellij-community,hurricup/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,petteyg/intellij-community,xfournet/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,fnouama/intellij-community,amith01994/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,jexp/idea2,orekyuu/intellij-community,nicolargo/intellij-community,izonder/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,amith01994/intellij-community,caot/intellij-community,apixandru/intellij-community,consulo/consulo,vvv1559/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,adedayo/intellij-community,slisson/intellij-community,jagguli/intellij-community,slisson/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,vladmm/intellij-community,adedayo/intellij-community,petteyg/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,adedayo/intellij-community,signed/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,blademainer/intellij-community,dslomov/intellij-community,kdwink/intellij-community,dslomov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,amith01994/intellij-community,semonte/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,dslomov/intellij-community,holmes/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,robovm/robovm-studio,jagguli/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,allotria/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,robovm/robovm-studio,joewalnes/idea-community,ahb0327/intellij-community,xfournet/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,da1z/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,izonder/intellij-community,dslomov/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,supersven/intellij-community,fitermay/intellij-community,samthor/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,semonte/intellij-community,samthor/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,clumsy/intellij-community,jagguli/intellij-community,clumsy/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,da1z/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ryano144/intellij-community,hurricup/intellij-community,samthor/intellij-community,ibinti/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,izonder/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,clumsy/intellij-community,signed/intellij-community,kdwink/intellij-community,robovm/robovm-studio,fitermay/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,allotria/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,kool79/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,caot/intellij-community,lucafavatella/intellij-community,jexp/idea2,TangHao1987/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,caot/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,supersven/intellij-community,youdonghai/intellij-community,jexp/idea2,slisson/intellij-community,hurricup/intellij-community,signed/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,ryano144/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,holmes/intellij-community,consulo/consulo,hurricup/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,consulo/consulo,caot/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,asedunov/intellij-community,diorcety/intellij-community,jagguli/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,fitermay/intellij-community,diorcety/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,consulo/consulo,caot/intellij-community,izonder/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,da1z/intellij-community,fnouama/intellij-community,clumsy/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,retomerz/intellij-community,ibinti/intellij-community,hurricup/intellij-community,vladmm/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,asedunov/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,izonder/intellij-community,xfournet/intellij-community,adedayo/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,caot/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,caot/intellij-community,slisson/intellij-community,supersven/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,amith01994/intellij-community,semonte/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,signed/intellij-community,kdwink/intellij-community,ibinti/intellij-community,allotria/intellij-community,ernestp/consulo,tmpgit/intellij-community,asedunov/intellij-community,da1z/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,caot/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,signed/intellij-community,dslomov/intellij-community,joewalnes/idea-community,semonte/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ibinti/intellij-community,retomerz/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,xfournet/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,kool79/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,caot/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,tmpgit/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,hurricup/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,kool79/intellij-community,retomerz/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ernestp/consulo,tmpgit/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,signed/intellij-community,allotria/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ernestp/consulo,holmes/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,kool79/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,semonte/intellij-community,retomerz/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,akosyakov/intellij-community,jexp/idea2,ernestp/consulo,jagguli/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,asedunov/intellij-community,blademainer/intellij-community,diorcety/intellij-community,amith01994/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,samthor/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,semonte/intellij-community,ernestp/consulo,pwoodworth/intellij-community,retomerz/intellij-community,signed/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,slisson/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,holmes/intellij-community,allotria/intellij-community,ernestp/consulo,robovm/robovm-studio,gnuhub/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,asedunov/intellij-community,signed/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ryano144/intellij-community,signed/intellij-community,vladmm/intellij-community,kdwink/intellij-community,robovm/robovm-studio,da1z/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,semonte/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,blademainer/intellij-community,fnouama/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,jexp/idea2,FHannes/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,signed/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,holmes/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,consulo/consulo,alphafoobar/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,allotria/intellij-community,slisson/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,supersven/intellij-community,ibinti/intellij-community,petteyg/intellij-community,allotria/intellij-community,samthor/intellij-community,semonte/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,supersven/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,caot/intellij-community,fitermay/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,jagguli/intellij-community,izonder/intellij-community,holmes/intellij-community,xfournet/intellij-community | /*
* User: anna
* Date: 14-May-2009
*/
package com.intellij.profile.codeInspection.ui.actions;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.ex.Descriptor;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.ScopeToolState;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.profile.codeInspection.ui.InspectionConfigTreeNode;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.Icons;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.util.*;
public abstract class AddScopeAction extends AnAction {
private final Tree myTree;
private static final Logger LOG = Logger.getInstance("#" + AddScopeAction.class.getName());
public AddScopeAction(Tree tree) {
super("Add Scope", "Add Scope", Icons.ADD_ICON);
myTree = tree;
registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
}
@Override
public void update(AnActionEvent e) {
final Presentation presentation = e.getPresentation();
presentation.setEnabled(false);
if (getSelectedProfile() == null) return;
final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext());
if (project == null) return;
final InspectionConfigTreeNode[] nodes = myTree.getSelectedNodes(InspectionConfigTreeNode.class, null);
if (nodes.length > 0) {
final InspectionConfigTreeNode node = nodes[0];
final Descriptor descriptor = node.getDesriptor();
if (descriptor != null && node.getScope() == null && !getAvailableScopes(descriptor, project).isEmpty()) {
presentation.setEnabled(true);
}
}
}
@Override
public void actionPerformed(AnActionEvent e) {
final InspectionConfigTreeNode[] nodes = myTree.getSelectedNodes(InspectionConfigTreeNode.class, null);
final InspectionConfigTreeNode node = nodes[0];
final Descriptor descriptor = node.getDesriptor();
LOG.assertTrue(descriptor != null);
final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext());
final InspectionProfileEntry tool = descriptor.getTool(); //copy
final List<String> availableScopes = getAvailableScopes(descriptor, project);
final int idx = Messages.showChooseDialog(myTree, "Scope:", "Choose Scope",
availableScopes.toArray(new String[availableScopes.size()]), availableScopes.get(0), Messages.getQuestionIcon());
if (idx == -1) return;
final NamedScope chosenScope = NamedScopesHolder.getScope(project, availableScopes.get(idx));
final ScopeToolState scopeToolState = getSelectedProfile().addScope(tool, chosenScope,
getSelectedProfile().getErrorLevel(descriptor.getKey(), chosenScope),
getSelectedProfile().isToolEnabled(descriptor.getKey()));
final Descriptor addedDescriptor = new Descriptor(scopeToolState, getSelectedProfile());
if (node.getChildCount() == 0) {
node.add(new InspectionConfigTreeNode(descriptor, scopeToolState, true, true, false));
}
node.insert(new InspectionConfigTreeNode(addedDescriptor, scopeToolState, false, true, false), 0);
node.setInspectionNode(false);
node.isProperSetting = getSelectedProfile().isProperSetting(HighlightDisplayKey.find(tool.getShortName()));
((DefaultTreeModel)myTree.getModel()).reload(node);
myTree.expandPath(new TreePath(node.getPath()));
myTree.revalidate();
}
private List<String> getAvailableScopes(Descriptor descriptor, Project project) {
final ArrayList<NamedScope> scopes = new ArrayList<NamedScope>();
for (NamedScopesHolder holder : NamedScopesHolder.getAllNamedScopeHolders(project)) {
Collections.addAll(scopes, holder.getScopes());
}
final Set<NamedScope> used = new HashSet<NamedScope>();
final List<ScopeToolState> nonDefaultTools = getSelectedProfile().getNonDefaultTools(descriptor.getKey().toString());
if (nonDefaultTools != null) {
for (ScopeToolState state : nonDefaultTools) {
used.add(state.getScope());
}
}
scopes.removeAll(used);
final List<String> availableScopes = new ArrayList<String>();
for (NamedScope scope : scopes) {
availableScopes.add(scope.getName());
}
return availableScopes;
}
protected abstract InspectionProfileImpl getSelectedProfile();
} | lang-impl/src/com/intellij/profile/codeInspection/ui/actions/AddScopeAction.java | /*
* User: anna
* Date: 14-May-2009
*/
package com.intellij.profile.codeInspection.ui.actions;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.ex.Descriptor;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.ScopeToolState;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.profile.codeInspection.ui.InspectionConfigTreeNode;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.Icons;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.util.*;
public abstract class AddScopeAction extends AnAction {
private final Tree myTree;
private static final Logger LOG = Logger.getInstance("#" + AddScopeAction.class.getName());
public AddScopeAction(Tree tree) {
super("Add Scope", "Add Scope", Icons.ADD_ICON);
myTree = tree;
registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
}
@Override
public void update(AnActionEvent e) {
final Presentation presentation = e.getPresentation();
presentation.setEnabled(false);
if (getSelectedProfile() == null) return;
final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext());
if (project == null) return;
final InspectionConfigTreeNode[] nodes = myTree.getSelectedNodes(InspectionConfigTreeNode.class, null);
if (nodes.length > 0) {
final InspectionConfigTreeNode node = nodes[0];
final Descriptor descriptor = node.getDesriptor();
if (descriptor != null && node.getScope() == null && !getAvailableScopes(descriptor, project).isEmpty()) {
presentation.setEnabled(true);
}
}
}
@Override
public void actionPerformed(AnActionEvent e) {
final InspectionConfigTreeNode[] nodes = myTree.getSelectedNodes(InspectionConfigTreeNode.class, null);
final InspectionConfigTreeNode node = nodes[0];
final Descriptor descriptor = node.getDesriptor();
LOG.assertTrue(descriptor != null);
final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext());
final InspectionProfileEntry tool = descriptor.getTool(); //copy
final List<String> availableScopes = getAvailableScopes(descriptor, project);
final int idx = Messages.showChooseDialog(myTree, "Scope:", "Choose Scope",
availableScopes.toArray(new String[availableScopes.size()]), availableScopes.get(0), Messages.getQuestionIcon());
if (idx == -1) return;
final ScopeToolState scopeToolState = getSelectedProfile().addScope(tool, NamedScopesHolder.getScope(project, availableScopes.get(idx)),
descriptor.getLevel(), tool.isEnabledByDefault());
final Descriptor addedDescriptor = new Descriptor(scopeToolState, getSelectedProfile());
if (node.getChildCount() == 0) {
node.add(new InspectionConfigTreeNode(descriptor, scopeToolState, true, true, false));
}
node.insert(new InspectionConfigTreeNode(addedDescriptor, scopeToolState, false, true, false), 0);
node.setInspectionNode(false);
node.isProperSetting = getSelectedProfile().isProperSetting(HighlightDisplayKey.find(tool.getShortName()));
((DefaultTreeModel)myTree.getModel()).reload(node);
myTree.expandPath(new TreePath(node.getPath()));
myTree.revalidate();
}
private List<String> getAvailableScopes(Descriptor descriptor, Project project) {
final ArrayList<NamedScope> scopes = new ArrayList<NamedScope>();
for (NamedScopesHolder holder : NamedScopesHolder.getAllNamedScopeHolders(project)) {
Collections.addAll(scopes, holder.getScopes());
}
final Set<NamedScope> used = new HashSet<NamedScope>();
final List<ScopeToolState> nonDefaultTools = getSelectedProfile().getNonDefaultTools(descriptor.getKey().toString());
if (nonDefaultTools != null) {
for (ScopeToolState state : nonDefaultTools) {
used.add(state.getScope());
}
}
scopes.removeAll(used);
final List<String> availableScopes = new ArrayList<String>();
for (NamedScope scope : scopes) {
availableScopes.add(scope.getName());
}
return availableScopes;
}
protected abstract InspectionProfileImpl getSelectedProfile();
} | add scope with current settings (IDEADEV-36963)
| lang-impl/src/com/intellij/profile/codeInspection/ui/actions/AddScopeAction.java | add scope with current settings (IDEADEV-36963) | <ide><path>ang-impl/src/com/intellij/profile/codeInspection/ui/actions/AddScopeAction.java
<ide> final int idx = Messages.showChooseDialog(myTree, "Scope:", "Choose Scope",
<ide> availableScopes.toArray(new String[availableScopes.size()]), availableScopes.get(0), Messages.getQuestionIcon());
<ide> if (idx == -1) return;
<del> final ScopeToolState scopeToolState = getSelectedProfile().addScope(tool, NamedScopesHolder.getScope(project, availableScopes.get(idx)),
<del> descriptor.getLevel(), tool.isEnabledByDefault());
<add> final NamedScope chosenScope = NamedScopesHolder.getScope(project, availableScopes.get(idx));
<add> final ScopeToolState scopeToolState = getSelectedProfile().addScope(tool, chosenScope,
<add> getSelectedProfile().getErrorLevel(descriptor.getKey(), chosenScope),
<add> getSelectedProfile().isToolEnabled(descriptor.getKey()));
<ide> final Descriptor addedDescriptor = new Descriptor(scopeToolState, getSelectedProfile());
<ide> if (node.getChildCount() == 0) {
<ide> node.add(new InspectionConfigTreeNode(descriptor, scopeToolState, true, true, false)); |
|
Java | apache-2.0 | 6e872dad066c9b5d77e7a96fce3d5b6e65a284be | 0 | fivejjs/crawljax,xujun10110/crawljax,fivejjs/crawljax,bigplus/crawljax,cschroed-usgs/crawljax,aminmf/crawljax,aminmf/crawljax,xujun10110/crawljax,robertzas/crawljax,ntatsumi/crawljax,aminmf/crawljax,ntatsumi/crawljax,bigplus/crawljax,crawljax/crawljax,adini121/crawljax,bigplus/crawljax,cschroed-usgs/crawljax,robertzas/crawljax,adini121/crawljax,crawljax/crawljax,robertzas/crawljax,cschroed-usgs/crawljax,crawljax/crawljax,fivejjs/crawljax,bigplus/crawljax,crawljax/crawljax,ntatsumi/crawljax,adini121/crawljax,cschroed-usgs/crawljax,adini121/crawljax,robertzas/crawljax,fivejjs/crawljax,aminmf/crawljax,ntatsumi/crawljax,xujun10110/crawljax,xujun10110/crawljax | package com.crawljax.core;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.crawljax.core.ExitNotifier.ExitStatus;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.core.plugin.Plugins;
import com.crawljax.core.state.StateVertex;
import com.crawljax.di.CrawlSessionProvider;
/**
* Starts and shuts down the crawl.
*/
@Singleton
public class CrawlController implements Callable<CrawlSession> {
private static final Logger LOG = LoggerFactory.getLogger(CrawlController.class);
private final Provider<CrawlTaskConsumer> consumerFactory;
private final ExecutorService executor;
private final CrawljaxConfiguration config;
private final CrawlSessionProvider crawlSessionProvider;
private final Plugins plugins;
private final long maximumCrawlTime;
private final ExitNotifier exitNotifier;
private ExitStatus exitReason;
@Inject
CrawlController(ExecutorService executor, Provider<CrawlTaskConsumer> consumerFactory,
CrawljaxConfiguration config, ExitNotifier exitNotifier,
CrawlSessionProvider crawlSessionProvider) {
this.executor = executor;
this.consumerFactory = consumerFactory;
this.exitNotifier = exitNotifier;
this.config = config;
this.plugins = config.getPlugins();
this.crawlSessionProvider = crawlSessionProvider;
this.maximumCrawlTime = config.getMaximumRuntime();
}
/**
* Run the configured crawl.
*
* @return
*/
@Override
public CrawlSession call() {
setMaximumCrawlTimeIfNeeded();
plugins.runPreCrawlingPlugins(config);
CrawlTaskConsumer firstConsumer = consumerFactory.get();
StateVertex firstState = firstConsumer.crawlIndex();
crawlSessionProvider.setup(firstState);
plugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);
executeConsumers(firstConsumer);
return crawlSessionProvider.get();
}
/**
* @return The {@link ExitStatus} crawljax stopped or <code>null</code> when it hasn't stopped
* yet.
*/
public ExitStatus getReason() {
return exitReason;
}
private void setMaximumCrawlTimeIfNeeded() {
if (maximumCrawlTime == 0) {
return;
}
executor.submit(new Runnable() {
@Override
public void run() {
try {
LOG.debug("Waiting {} before killing the crawler", maximumCrawlTime);
Thread.sleep(maximumCrawlTime);
LOG.info("Time is up! Shutting down...");
exitNotifier.signalTimeIsUp();
} catch (InterruptedException e) {
LOG.debug("Crawler finished before maximum crawltime exceeded");
}
}
});
}
private void executeConsumers(CrawlTaskConsumer firstConsumer) {
LOG.debug("Starting {} consumers", config.getBrowserConfig().getNumberOfBrowsers());
executor.submit(firstConsumer);
for (int i = 1; i < config.getBrowserConfig().getNumberOfBrowsers(); i++) {
executor.submit(consumerFactory.get());
}
try {
exitReason = exitNotifier.awaitTermination();
} catch (InterruptedException e) {
LOG.warn("The crawl was interrupted before it finished. Shutting down...");
exitReason = ExitStatus.ERROR;
} finally {
shutDown();
plugins.runPostCrawlingPlugins(crawlSessionProvider.get(), exitReason);
LOG.info("Shutdown process complete");
}
}
private void shutDown() {
LOG.info("Received shutdown notice. Reason is {}", exitReason);
executor.shutdownNow();
try {
LOG.debug("Waiting for task consumers to stop...");
executor.awaitTermination(15, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.warn("Interrupted before being able to shut down executor pool", e);
exitReason = ExitStatus.ERROR;
}
LOG.debug("terminated");
}
void stop() {
exitNotifier.stop();
}
}
| core/src/main/java/com/crawljax/core/CrawlController.java | package com.crawljax.core;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.crawljax.core.ExitNotifier.ExitStatus;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.core.plugin.Plugins;
import com.crawljax.core.state.StateVertex;
import com.crawljax.di.CrawlSessionProvider;
/**
* Starts and shuts down the crawl.
*/
@Singleton
public class CrawlController implements Callable<CrawlSession> {
private static final Logger LOG = LoggerFactory.getLogger(CrawlController.class);
private final Provider<CrawlTaskConsumer> consumerFactory;
private final ExecutorService executor;
private final CrawljaxConfiguration config;
private final CrawlSessionProvider crawlSessionProvider;
private final Plugins plugins;
private final long maximumCrawlTime;
private final ExitNotifier exitNotifier;
private ExitStatus exitReason;
@Inject
CrawlController(ExecutorService executor, Provider<CrawlTaskConsumer> consumerFactory,
CrawljaxConfiguration config, ExitNotifier exitNotifier,
CrawlSessionProvider crawlSessionProvider) {
this.executor = executor;
this.consumerFactory = consumerFactory;
this.exitNotifier = exitNotifier;
this.config = config;
this.plugins = config.getPlugins();
this.crawlSessionProvider = crawlSessionProvider;
this.maximumCrawlTime = config.getMaximumRuntime();
}
/**
* Run the configured crawl.
*
* @return
*/
@Override
public CrawlSession call() {
plugins.runProxyServerPlugins(config.getProxyConfiguration());
setMaximumCrawlTimeIfNeeded();
plugins.runPreCrawlingPlugins(config);
CrawlTaskConsumer firstConsumer = consumerFactory.get();
StateVertex firstState = firstConsumer.crawlIndex();
crawlSessionProvider.setup(firstState);
plugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);
executeConsumers(firstConsumer);
return crawlSessionProvider.get();
}
/**
* @return The {@link ExitStatus} crawljax stopped or <code>null</code> when it hasn't stopped
* yet.
*/
public ExitStatus getReason() {
return exitReason;
}
private void setMaximumCrawlTimeIfNeeded() {
if (maximumCrawlTime == 0) {
return;
}
executor.submit(new Runnable() {
@Override
public void run() {
try {
LOG.debug("Waiting {} before killing the crawler", maximumCrawlTime);
Thread.sleep(maximumCrawlTime);
LOG.info("Time is up! Shutting down...");
exitNotifier.signalTimeIsUp();
} catch (InterruptedException e) {
LOG.debug("Crawler finished before maximum crawltime exceeded");
}
}
});
}
private void executeConsumers(CrawlTaskConsumer firstConsumer) {
LOG.debug("Starting {} consumers", config.getBrowserConfig().getNumberOfBrowsers());
executor.submit(firstConsumer);
for (int i = 1; i < config.getBrowserConfig().getNumberOfBrowsers(); i++) {
executor.submit(consumerFactory.get());
}
try {
exitReason = exitNotifier.awaitTermination();
} catch (InterruptedException e) {
LOG.warn("The crawl was interrupted before it finished. Shutting down...");
exitReason = ExitStatus.ERROR;
} finally {
shutDown();
plugins.runPostCrawlingPlugins(crawlSessionProvider.get(), exitReason);
LOG.info("Shutdown process complete");
}
}
private void shutDown() {
LOG.info("Received shutdown notice. Reason is {}", exitReason);
executor.shutdownNow();
try {
LOG.debug("Waiting for task consumers to stop...");
executor.awaitTermination(15, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.warn("Interrupted before being able to shut down executor pool", e);
exitReason = ExitStatus.ERROR;
}
LOG.debug("terminated");
}
void stop() {
exitNotifier.stop();
}
}
| Fixed broken reference to proxy plugin
| core/src/main/java/com/crawljax/core/CrawlController.java | Fixed broken reference to proxy plugin | <ide><path>ore/src/main/java/com/crawljax/core/CrawlController.java
<ide> */
<ide> @Override
<ide> public CrawlSession call() {
<del> plugins.runProxyServerPlugins(config.getProxyConfiguration());
<ide> setMaximumCrawlTimeIfNeeded();
<ide> plugins.runPreCrawlingPlugins(config);
<ide> CrawlTaskConsumer firstConsumer = consumerFactory.get(); |
|
Java | apache-2.0 | 36c9ef96bf09101d202368235e30c749ea214eae | 0 | daleqq/opensymphony-quartz-backup,chandrasekhar4u/opensymphony-quartz-backup,vthriller/opensymphony-quartz-backup,chandrasekhar4u/opensymphony-quartz-backup,eric-hsu/opensymphony-quartz-backup,vthriller/opensymphony-quartz-backup,eric-hsu/opensymphony-quartz-backup,dbahar/opensymphony-quartz-backup,feigeai/opensymphony-quartz-backup,dbahar/opensymphony-quartz-backup,dbahar/opensymphony-quartz-backup,vthriller/opensymphony-quartz-backup,daleqq/opensymphony-quartz-backup,feigeai/opensymphony-quartz-backup,chandrasekhar4u/opensymphony-quartz-backup,eric-hsu/opensymphony-quartz-backup,daleqq/opensymphony-quartz-backup,feigeai/opensymphony-quartz-backup | /*
* Copyright 2004-2005 OpenSymphony
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
/*
* Previously Copyright (c) 2001-2004 James House
*/
package org.quartz.impl;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.AccessControlException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerConfigException;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerListener;
import org.quartz.core.JobRunShellFactory;
import org.quartz.core.QuartzScheduler;
import org.quartz.core.QuartzSchedulerResources;
import org.quartz.core.SchedulingContext;
import org.quartz.ee.jta.JTAJobRunShellFactory;
import org.quartz.ee.jta.UserTransactionHelper;
import org.quartz.impl.jdbcjobstore.JobStoreSupport;
import org.quartz.simpl.RAMJobStore;
import org.quartz.simpl.SimpleThreadPool;
import org.quartz.spi.ClassLoadHelper;
import org.quartz.spi.InstanceIdGenerator;
import org.quartz.spi.JobFactory;
import org.quartz.spi.JobStore;
import org.quartz.spi.SchedulerPlugin;
import org.quartz.spi.ThreadPool;
import org.quartz.utils.ConnectionProvider;
import org.quartz.utils.DBConnectionManager;
import org.quartz.utils.JNDIConnectionProvider;
import org.quartz.utils.PoolingConnectionProvider;
import org.quartz.utils.PropertiesParser;
/**
* <p>
* An implementation of <code>{@link org.quartz.SchedulerFactory}</code> that
* does all of its work of creating a <code>QuartzScheduler</code> instance
* based on the contenents of a <code>Properties</code> file.
* </p>
*
* <p>
* By default a properties file named "quartz.properties" is loaded from the
* 'current working directory'. If that fails, then the "quartz.properties"
* file located (as a resource) in the org/quartz package is loaded. If you
* wish to use a file other than these defaults, you must define the system
* property 'org.quartz.properties' to point to the file you want.
* </p>
*
* <p>
* See the sample properties files that are distributed with Quartz for
* information about the various settings available within the file.
* </p>
*
* <p>
* Alternatively, you can explicitly initialize the factory by calling one of
* the <code>initialize(xx)</code> methods before calling <code>getScheduler()</code>.
* </p>
*
* <p>
* Instances of the specified <code>{@link org.quartz.spi.JobStore}</code>,
* <code>{@link org.quartz.spi.ThreadPool}</code>, classes will be created
* by name, and then any additional properties specified for them in the config
* file will be set on the instance by calling an equivalent 'set' method. For
* example if the properties file contains the property
* 'org.quartz.jobStore.myProp = 10' then after the JobStore class has been
* instantiated, the method 'setMyProp()' will be called on it. Type conversion
* to primitive Java types (int, long, float, double, boolean, and String) are
* performed before calling the property's setter method.
* </p>
*
* @author James House
* @author Anthony Eden
* @author Mohammad Rezaei
*/
public class StdSchedulerFactory implements SchedulerFactory {
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Constants.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
public static final String PROPERTIES_FILE = "org.quartz.properties";
public static final String PROP_SCHED_INSTANCE_NAME = "org.quartz.scheduler.instanceName";
public static final String PROP_SCHED_INSTANCE_ID = "org.quartz.scheduler.instanceId";
public static final String PROP_SCHED_INSTANCE_ID_GENERATOR_PREFIX = "org.quartz.scheduler.instanceIdGenerator";
public static final String PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS =
PROP_SCHED_INSTANCE_ID_GENERATOR_PREFIX + ".class";
public static final String PROP_SCHED_THREAD_NAME = "org.quartz.scheduler.threadName";
public static final String PROP_SCHED_RMI_EXPORT = "org.quartz.scheduler.rmi.export";
public static final String PROP_SCHED_RMI_PROXY = "org.quartz.scheduler.rmi.proxy";
public static final String PROP_SCHED_RMI_HOST = "org.quartz.scheduler.rmi.registryHost";
public static final String PROP_SCHED_RMI_PORT = "org.quartz.scheduler.rmi.registryPort";
public static final String PROP_SCHED_RMI_SERVER_PORT = "org.quartz.scheduler.rmi.serverPort";
public static final String PROP_SCHED_RMI_CREATE_REGISTRY = "org.quartz.scheduler.rmi.createRegistry";
public static final String PROP_SCHED_WRAP_JOB_IN_USER_TX = "org.quartz.scheduler.wrapJobExecutionInUserTransaction";
public static final String PROP_SCHED_USER_TX_URL = "org.quartz.scheduler.userTransactionURL";
public static final String PROP_SCHED_IDLE_WAIT_TIME = "org.quartz.scheduler.idleWaitTime";
public static final String PROP_SCHED_DB_FAILURE_RETRY_INTERVAL = "org.quartz.scheduler.dbFailureRetryInterval";
public static final String PROP_SCHED_CLASS_LOAD_HELPER_CLASS = "org.quartz.scheduler.classLoadHelper.class";
public static final String PROP_SCHED_JOB_FACTORY_CLASS = "org.quartz.scheduler.jobFactory.class";
public static final String PROP_SCHED_JOB_FACTORY_PREFIX = "org.quartz.scheduler.jobFactory";
public static final String PROP_SCHED_CONTEXT_PREFIX = "org.quartz.context.key";
public static final String PROP_THREAD_POOL_PREFIX = "org.quartz.threadPool";
public static final String PROP_THREAD_POOL_CLASS = "org.quartz.threadPool.class";
public static final String PROP_JOB_STORE_PREFIX = "org.quartz.jobStore";
public static final String PROP_JOB_STORE_CLASS = "org.quartz.jobStore.class";
public static final String PROP_JOB_STORE_USE_PROP = "org.quartz.jobStore.useProperties";
public static final String PROP_DATASOURCE_PREFIX = "org.quartz.dataSource";
public static final String PROP_CONNECTION_PROVIDER_CLASS = "connectionProvider.class";
public static final String PROP_DATASOURCE_DRIVER = "driver";
public static final String PROP_DATASOURCE_URL = "URL";
public static final String PROP_DATASOURCE_USER = "user";
public static final String PROP_DATASOURCE_PASSWORD = "password";
public static final String PROP_DATASOURCE_MAX_CONNECTIONS = "maxConnections";
public static final String PROP_DATASOURCE_VALIDATION_QUERY = "validationQuery";
public static final String PROP_DATASOURCE_JNDI_URL = "jndiURL";
public static final String PROP_DATASOURCE_JNDI_ALWAYS_LOOKUP = "jndiAlwaysLookup";
public static final String PROP_DATASOURCE_JNDI_INITIAL = "java.naming.factory.initial";
public static final String PROP_DATASOURCE_JNDI_PROVDER = "java.naming.provider.url";
public static final String PROP_DATASOURCE_JNDI_PRINCIPAL = "java.naming.security.principal";
public static final String PROP_DATASOURCE_JNDI_CREDENTIALS = "java.naming.security.credentials";
public static final String PROP_PLUGIN_PREFIX = "org.quartz.plugin";
public static final String PROP_PLUGIN_CLASS = "class";
public static final String PROP_JOB_LISTENER_PREFIX = "org.quartz.jobListener";
public static final String PROP_TRIGGER_LISTENER_PREFIX = "org.quartz.triggerListener";
public static final String PROP_LISTENER_CLASS = "class";
public static final String DEFAULT_INSTANCE_ID = "NON_CLUSTERED";
public static final String AUTO_GENERATE_INSTANCE_ID = "AUTO";
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Data members.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
private SchedulerException initException = null;
private String propSrc = null;
private PropertiesParser cfg;
private final Log log = LogFactory.getLog(getClass());
// private Scheduler scheduler;
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Constructors.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* Create an uninitialized StdSchedulerFactory.
*/
public StdSchedulerFactory() {
}
/**
* Create a StdSchedulerFactory that has been initialized via
* <code>{@link #initialize(Properties)}</code>.
*
* @see #initialize(Properties)
*/
public StdSchedulerFactory(Properties props) throws SchedulerException {
initialize(props);
}
/**
* Create a StdSchedulerFactory that has been initialized via
* <code>{@link #initialize(String)}</code>.
*
* @see #initialize(String)
*/
public StdSchedulerFactory(String fileName) throws SchedulerException {
initialize(fileName);
}
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Interface.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
public Log getLog() {
return log;
}
/**
* <p>
* Initialize the <code>{@link org.quartz.SchedulerFactory}</code> with
* the contents of a <code>Properties</code> file and overriding System
* properties.
* </p>
*
* <p>
* By default a properties file named "quartz.properties" is loaded from
* the 'current working directory'. If that fails, then the
* "quartz.properties" file located (as a resource) in the org/quartz
* package is loaded. If you wish to use a file other than these defaults,
* you must define the system property 'org.quartz.properties' to point to
* the file you want.
* </p>
*
* <p>
* System properties (environment variables, and -D definitions on the
* command-line when running the JVM) override any properties in the
* loaded file. For this reason, you may want to use a different initialize()
* method if your application security policy prohibits access to
* <code>{@link java.lang.System#getProperties()}</code>.
* </p>
*/
public void initialize() throws SchedulerException {
// short-circuit if already initialized
if (cfg != null) {
return;
}
if (initException != null) {
throw initException;
}
String requestedFile = System.getProperty(PROPERTIES_FILE);
String propFileName = requestedFile != null ? requestedFile
: "quartz.properties";
File propFile = new File(propFileName);
Properties props = new Properties();
if (propFile.exists()) {
try {
if (requestedFile != null) {
propSrc = "specified file: '" + requestedFile + "'";
} else {
propSrc = "default file in current working dir: 'quartz.properties'";
}
props.load(new BufferedInputStream(new FileInputStream(
propFileName)));
} catch (IOException ioe) {
initException = new SchedulerException("Properties file: '"
+ propFileName + "' could not be read.", ioe);
throw initException;
}
} else if (requestedFile != null) {
InputStream in =
Thread.currentThread().getContextClassLoader().getResourceAsStream(requestedFile);
if(in == null) {
initException = new SchedulerException("Properties file: '"
+ requestedFile + "' could not be found.");
throw initException;
}
propSrc = "specified file: '" + requestedFile + "' in the class resource path.";
try {
props.load(new BufferedInputStream(in));
} catch (IOException ioe) {
initException = new SchedulerException("Properties file: '"
+ requestedFile + "' could not be read.", ioe);
throw initException;
}
} else {
propSrc = "default resource file in Quartz package: 'quartz.properties'";
InputStream in = getClass().getClassLoader().getResourceAsStream(
"quartz.properties");
if (in == null) {
in = getClass().getClassLoader().getResourceAsStream(
"/quartz.properties");
}
if (in == null) {
in = getClass().getClassLoader().getResourceAsStream(
"org/quartz/quartz.properties");
}
if (in == null) {
initException = new SchedulerException(
"Default quartz.properties not found in class path");
throw initException;
}
try {
props.load(in);
} catch (IOException ioe) {
initException = new SchedulerException(
"Resource properties file: 'org/quartz/quartz.properties' "
+ "could not be read from the classpath.", ioe);
throw initException;
}
}
initialize(overrideWithSysProps(props));
}
/**
* Add all System properties to the given <code>props</code>. Will override
* any properties that already exist in the given <code>props</code>.
*/
private Properties overrideWithSysProps(Properties props) {
Properties sysProps = null;
try {
sysProps = System.getProperties();
} catch (AccessControlException e) {
getLog().warn(
"Skipping overriding quartz properties with System properties " +
"during initialization because of an AccessControlException. " +
"This is likely due to not having read/write access for " +
"java.util.PropertyPermission as required by java.lang.System.getProperties(). " +
"To resolve this warning, either add this permission to your policy file or " +
"use a non-default version of initialize().",
e);
}
if (sysProps != null) {
props.putAll(sysProps);
}
return props;
}
/**
* <p>
* Initialize the <code>{@link org.quartz.SchedulerFactory}</code> with
* the contenents of the <code>Properties</code> file with the given
* name.
* </p>
*/
public void initialize(String filename) throws SchedulerException {
// short-circuit if already initialized
if (cfg != null) {
return;
}
if (initException != null) {
throw initException;
}
InputStream is = null;
Properties props = new Properties();
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
try {
if(is != null) {
is = new BufferedInputStream(is);
propSrc = "the specified file : '" + filename + "' from the class resource path.";
} else {
is = new BufferedInputStream(new FileInputStream(filename));
propSrc = "the specified file : '" + filename + "'";
}
props.load(is);
} catch (IOException ioe) {
initException = new SchedulerException("Properties file: '"
+ filename + "' could not be read.", ioe);
throw initException;
}
initialize(props);
}
/**
* <p>
* Initialize the <code>{@link org.quartz.SchedulerFactory}</code> with
* the contenents of the <code>Properties</code> file opened with the
* given <code>InputStream</code>.
* </p>
*/
public void initialize(InputStream propertiesStream)
throws SchedulerException {
// short-circuit if already initialized
if (cfg != null) {
return;
}
if (initException != null) {
throw initException;
}
Properties props = new Properties();
if (propertiesStream != null) {
try {
props.load(propertiesStream);
propSrc = "an externally opened InputStream.";
} catch (IOException e) {
initException = new SchedulerException(
"Error loading property data from InputStream", e);
throw initException;
}
} else {
initException = new SchedulerException(
"Error loading property data from InputStream - InputStream is null.");
throw initException;
}
initialize(props);
}
/**
* <p>
* Initialize the <code>{@link org.quartz.SchedulerFactory}</code> with
* the contenents of the given <code>Properties</code> object.
* </p>
*/
public void initialize(Properties props) throws SchedulerException {
if (propSrc == null) {
propSrc = "an externally provided properties instance.";
}
this.cfg = new PropertiesParser(props);
}
private Scheduler instantiate() throws SchedulerException {
if (cfg == null) {
initialize();
}
if (initException != null) {
throw initException;
}
JobStore js = null;
ThreadPool tp = null;
QuartzScheduler qs = null;
SchedulingContext schedCtxt = null;
DBConnectionManager dbMgr = null;
String instanceIdGeneratorClass = null;
Properties tProps = null;
String userTXLocation = null;
boolean wrapJobInTx = false;
boolean autoId = false;
long idleWaitTime = -1;
long dbFailureRetry = -1;
String classLoadHelperClass;
String jobFactoryClass;
SchedulerRepository schedRep = SchedulerRepository.getInstance();
// Get Scheduler Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String schedName = cfg.getStringProperty(PROP_SCHED_INSTANCE_NAME,
"QuartzScheduler");
String threadName = cfg.getStringProperty(PROP_SCHED_THREAD_NAME,
schedName + "_QuartzSchedulerThread");
String schedInstId = cfg.getStringProperty(PROP_SCHED_INSTANCE_ID,
DEFAULT_INSTANCE_ID);
if (schedInstId.equals(AUTO_GENERATE_INSTANCE_ID)) {
autoId = true;
instanceIdGeneratorClass = cfg.getStringProperty(
PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS,
"org.quartz.simpl.SimpleInstanceIdGenerator");
}
userTXLocation = cfg.getStringProperty(PROP_SCHED_USER_TX_URL,
userTXLocation);
if (userTXLocation != null && userTXLocation.trim().length() == 0) {
userTXLocation = null;
}
classLoadHelperClass = cfg.getStringProperty(
PROP_SCHED_CLASS_LOAD_HELPER_CLASS,
"org.quartz.simpl.CascadingClassLoadHelper");
wrapJobInTx = cfg.getBooleanProperty(PROP_SCHED_WRAP_JOB_IN_USER_TX,
wrapJobInTx);
jobFactoryClass = cfg.getStringProperty(
PROP_SCHED_JOB_FACTORY_CLASS, null);
idleWaitTime = cfg.getLongProperty(PROP_SCHED_IDLE_WAIT_TIME,
idleWaitTime);
dbFailureRetry = cfg.getLongProperty(
PROP_SCHED_DB_FAILURE_RETRY_INTERVAL, dbFailureRetry);
boolean rmiExport = cfg
.getBooleanProperty(PROP_SCHED_RMI_EXPORT, false);
boolean rmiProxy = cfg.getBooleanProperty(PROP_SCHED_RMI_PROXY, false);
String rmiHost = cfg
.getStringProperty(PROP_SCHED_RMI_HOST, "localhost");
int rmiPort = cfg.getIntProperty(PROP_SCHED_RMI_PORT, 1099);
int rmiServerPort = cfg.getIntProperty(PROP_SCHED_RMI_SERVER_PORT, -1);
String rmiCreateRegistry = cfg.getStringProperty(
PROP_SCHED_RMI_CREATE_REGISTRY,
QuartzSchedulerResources.CREATE_REGISTRY_NEVER);
Properties schedCtxtProps = cfg.getPropertyGroup(PROP_SCHED_CONTEXT_PREFIX, true);
// If Proxying to remote scheduler, short-circuit here...
// ~~~~~~~~~~~~~~~~~~
if (rmiProxy) {
if (autoId) {
schedInstId = DEFAULT_INSTANCE_ID;
}
schedCtxt = new SchedulingContext();
schedCtxt.setInstanceId(schedInstId);
String uid = QuartzSchedulerResources.getUniqueIdentifier(
schedName, schedInstId);
RemoteScheduler remoteScheduler = new RemoteScheduler(schedCtxt,
uid, rmiHost, rmiPort);
schedRep.bind(remoteScheduler);
return remoteScheduler;
}
// Create class load helper
ClassLoadHelper loadHelper = null;
try {
loadHelper = (ClassLoadHelper) loadClass(classLoadHelperClass)
.newInstance();
} catch (Exception e) {
throw new SchedulerConfigException(
"Unable to instantiate class load helper class: "
+ e.getMessage(), e);
}
loadHelper.initialize();
JobFactory jobFactory = null;
if(jobFactoryClass != null) {
try {
jobFactory = (JobFactory) loadHelper.loadClass(jobFactoryClass)
.newInstance();
} catch (Exception e) {
throw new SchedulerConfigException(
"Unable to instantiate JobFactory class: "
+ e.getMessage(), e);
}
tProps = cfg.getPropertyGroup(PROP_SCHED_JOB_FACTORY_PREFIX, true);
try {
setBeanProps(jobFactory, tProps);
} catch (Exception e) {
initException = new SchedulerException("JobFactory class '"
+ jobFactoryClass + "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
}
InstanceIdGenerator instanceIdGenerator = null;
if(instanceIdGeneratorClass != null) {
try {
instanceIdGenerator = (InstanceIdGenerator) loadHelper.loadClass(instanceIdGeneratorClass)
.newInstance();
} catch (Exception e) {
throw new SchedulerConfigException(
"Unable to instantiate InstanceIdGenerator class: "
+ e.getMessage(), e);
}
}
tProps = cfg.getPropertyGroup(PROP_SCHED_INSTANCE_ID_GENERATOR_PREFIX, true);
try {
setBeanProps(instanceIdGenerator, tProps);
} catch (Exception e) {
initException = new SchedulerException("InstanceIdGenerator class '"
+ instanceIdGeneratorClass + "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
// Get ThreadPool Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String tpClass = cfg.getStringProperty(PROP_THREAD_POOL_CLASS, null);
if (tpClass == null) {
initException = new SchedulerException(
"ThreadPool class not specified. ",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
tp = (ThreadPool) loadHelper.loadClass(tpClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException("ThreadPool class '"
+ tpClass + "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
tProps = cfg.getPropertyGroup(PROP_THREAD_POOL_PREFIX, true);
try {
setBeanProps(tp, tProps);
} catch (Exception e) {
initException = new SchedulerException("ThreadPool class '"
+ tpClass + "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
// Get JobStore Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String jsClass = cfg.getStringProperty(PROP_JOB_STORE_CLASS,
RAMJobStore.class.getName());
if (jsClass == null) {
initException = new SchedulerException(
"JobStore class not specified. ",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
js = (JobStore) loadHelper.loadClass(jsClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException("JobStore class '" + jsClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
tProps = cfg.getPropertyGroup(PROP_JOB_STORE_PREFIX, true);
try {
setBeanProps(js, tProps);
} catch (Exception e) {
initException = new SchedulerException("JobStore class '" + jsClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
if (js instanceof org.quartz.impl.jdbcjobstore.JobStoreSupport) {
((org.quartz.impl.jdbcjobstore.JobStoreSupport) js)
.setInstanceId(schedInstId);
((org.quartz.impl.jdbcjobstore.JobStoreSupport) js)
.setInstanceName(schedName);
}
// Set up any DataSources
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String[] dsNames = cfg.getPropertyGroups(PROP_DATASOURCE_PREFIX);
for (int i = 0; i < dsNames.length; i++) {
PropertiesParser pp = new PropertiesParser(cfg.getPropertyGroup(
PROP_DATASOURCE_PREFIX + "." + dsNames[i], true));
String cpClass = pp.getStringProperty(PROP_CONNECTION_PROVIDER_CLASS, null);
// custom connectionProvider...
if(cpClass != null) {
ConnectionProvider cp = null;
try {
cp = (ConnectionProvider) loadHelper.loadClass(cpClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException("ConnectionProvider class '" + cpClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
// remove the class name, so it isn't attempted to be set
pp.getUnderlyingProperties().remove(
PROP_CONNECTION_PROVIDER_CLASS);
setBeanProps(cp, pp.getUnderlyingProperties());
} catch (Exception e) {
initException = new SchedulerException("ConnectionProvider class '" + cpClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
dbMgr = DBConnectionManager.getInstance();
dbMgr.addConnectionProvider(dsNames[i], cp);
} else {
String dsDriver = pp
.getStringProperty(PROP_DATASOURCE_DRIVER, null);
String dsURL = pp.getStringProperty(PROP_DATASOURCE_URL, null);
boolean dsAlwaysLookup = pp.getBooleanProperty(
PROP_DATASOURCE_JNDI_ALWAYS_LOOKUP, false);
String dsUser = pp.getStringProperty(PROP_DATASOURCE_USER, "");
String dsPass = pp.getStringProperty(PROP_DATASOURCE_PASSWORD, "");
int dsCnt = pp.getIntProperty(PROP_DATASOURCE_MAX_CONNECTIONS, 10);
String dsJndi = pp
.getStringProperty(PROP_DATASOURCE_JNDI_URL, null);
String dsJndiInitial = pp.getStringProperty(
PROP_DATASOURCE_JNDI_INITIAL, null);
String dsJndiProvider = pp.getStringProperty(
PROP_DATASOURCE_JNDI_PROVDER, null);
String dsJndiPrincipal = pp.getStringProperty(
PROP_DATASOURCE_JNDI_PRINCIPAL, null);
String dsJndiCredentials = pp.getStringProperty(
PROP_DATASOURCE_JNDI_CREDENTIALS, null);
String dsValidation = pp.getStringProperty(
PROP_DATASOURCE_VALIDATION_QUERY, null);
if (dsJndi != null) {
Properties props = null;
if (null != dsJndiInitial || null != dsJndiProvider
|| null != dsJndiPrincipal || null != dsJndiCredentials) {
props = new Properties();
if (dsJndiInitial != null) {
props.put(PROP_DATASOURCE_JNDI_INITIAL,
dsJndiInitial);
}
if (dsJndiProvider != null) {
props.put(PROP_DATASOURCE_JNDI_PROVDER,
dsJndiProvider);
}
if (dsJndiPrincipal != null) {
props.put(PROP_DATASOURCE_JNDI_PRINCIPAL,
dsJndiPrincipal);
}
if (dsJndiCredentials != null) {
props.put(PROP_DATASOURCE_JNDI_CREDENTIALS,
dsJndiCredentials);
}
}
JNDIConnectionProvider cp = new JNDIConnectionProvider(dsJndi,
props, dsAlwaysLookup);
dbMgr = DBConnectionManager.getInstance();
dbMgr.addConnectionProvider(dsNames[i], cp);
} else {
if (dsDriver == null) {
initException = new SchedulerException(
"Driver not specified for DataSource: "
+ dsNames[i]);
throw initException;
}
if (dsURL == null) {
initException = new SchedulerException(
"DB URL not specified for DataSource: "
+ dsNames[i]);
throw initException;
}
try {
PoolingConnectionProvider cp = new PoolingConnectionProvider(
dsDriver, dsURL, dsUser, dsPass, dsCnt,
dsValidation);
dbMgr = DBConnectionManager.getInstance();
dbMgr.addConnectionProvider(dsNames[i], cp);
} catch (SQLException sqle) {
initException = new SchedulerException(
"Could not initialize DataSource: " + dsNames[i],
sqle);
throw initException;
}
}
}
}
// Set up any SchedulerPlugins
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String[] pluginNames = cfg.getPropertyGroups(PROP_PLUGIN_PREFIX);
SchedulerPlugin[] plugins = new SchedulerPlugin[pluginNames.length];
for (int i = 0; i < pluginNames.length; i++) {
Properties pp = cfg.getPropertyGroup(PROP_PLUGIN_PREFIX + "."
+ pluginNames[i], true);
String plugInClass = pp.getProperty(PROP_PLUGIN_CLASS, null);
if (plugInClass == null) {
initException = new SchedulerException(
"SchedulerPlugin class not specified for plugin '"
+ pluginNames[i] + "'",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
SchedulerPlugin plugin = null;
try {
plugin = (SchedulerPlugin)
loadHelper.loadClass(plugInClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException(
"SchedulerPlugin class '" + plugInClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
setBeanProps(plugin, pp);
} catch (Exception e) {
initException = new SchedulerException(
"JobStore SchedulerPlugin '" + plugInClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
plugins[i] = plugin;
}
// Set up any JobListeners
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class[] strArg = new Class[] { String.class };
String[] jobListenerNames = cfg.getPropertyGroups(PROP_JOB_LISTENER_PREFIX);
JobListener[] jobListeners = new JobListener[jobListenerNames.length];
for (int i = 0; i < jobListenerNames.length; i++) {
Properties lp = cfg.getPropertyGroup(PROP_JOB_LISTENER_PREFIX + "."
+ jobListenerNames[i], true);
String listenerClass = lp.getProperty(PROP_LISTENER_CLASS, null);
if (listenerClass == null) {
initException = new SchedulerException(
"JobListener class not specified for listener '"
+ jobListenerNames[i] + "'",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
JobListener listener = null;
try {
listener = (JobListener)
loadHelper.loadClass(listenerClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException(
"JobListener class '" + listenerClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
Method nameSetter = listener.getClass().getMethod("setName", strArg);
if(nameSetter != null) {
nameSetter.invoke(listener, new Object[] {jobListenerNames[i] } );
}
setBeanProps(listener, lp);
} catch (Exception e) {
initException = new SchedulerException(
"JobListener '" + listenerClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
jobListeners[i] = listener;
}
// Set up any TriggerListeners
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String[] triggerListenerNames = cfg.getPropertyGroups(PROP_TRIGGER_LISTENER_PREFIX);
TriggerListener[] triggerListeners = new TriggerListener[triggerListenerNames.length];
for (int i = 0; i < triggerListenerNames.length; i++) {
Properties lp = cfg.getPropertyGroup(PROP_TRIGGER_LISTENER_PREFIX + "."
+ triggerListenerNames[i], true);
String listenerClass = lp.getProperty(PROP_LISTENER_CLASS, null);
if (listenerClass == null) {
initException = new SchedulerException(
"TriggerListener class not specified for listener '"
+ triggerListenerNames[i] + "'",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
TriggerListener listener = null;
try {
listener = (TriggerListener)
loadHelper.loadClass(listenerClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException(
"TriggerListener class '" + listenerClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
Method nameSetter = listener.getClass().getMethod("setName", strArg);
if(nameSetter != null) {
nameSetter.invoke(listener, new Object[] {triggerListenerNames[i] } );
}
setBeanProps(listener, lp);
} catch (Exception e) {
initException = new SchedulerException(
"TriggerListener '" + listenerClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
triggerListeners[i] = listener;
}
// Fire everything up
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
JobRunShellFactory jrsf = null; // Create correct run-shell factory...
UserTransactionHelper.setUserTxLocation(userTXLocation);
if (wrapJobInTx) {
jrsf = new JTAJobRunShellFactory();
} else {
jrsf = new StdJobRunShellFactory();
}
if (autoId) {
try {
schedInstId = DEFAULT_INSTANCE_ID;
if (js instanceof org.quartz.impl.jdbcjobstore.JobStoreSupport) {
if(((org.quartz.impl.jdbcjobstore.JobStoreSupport) js)
.isClustered()) {
schedInstId = instanceIdGenerator.generateInstanceId();
}
}
} catch (Exception e) {
getLog().error("Couldn't generate instance Id!", e);
throw new IllegalStateException(
"Cannot run without an instance id.");
}
}
if (js instanceof JobStoreSupport) {
JobStoreSupport jjs = (JobStoreSupport) js;
jjs.setInstanceId(schedInstId);
jjs.setDbRetryInterval(dbFailureRetry);
}
QuartzSchedulerResources rsrcs = new QuartzSchedulerResources();
rsrcs.setName(schedName);
rsrcs.setThreadName(threadName);
rsrcs.setInstanceId(schedInstId);
rsrcs.setJobRunShellFactory(jrsf);
if (rmiExport) {
rsrcs.setRMIRegistryHost(rmiHost);
rsrcs.setRMIRegistryPort(rmiPort);
rsrcs.setRMIServerPort(rmiServerPort);
rsrcs.setRMICreateRegistryStrategy(rmiCreateRegistry);
}
rsrcs.setThreadPool(tp);
if(tp instanceof SimpleThreadPool) {
((SimpleThreadPool)tp).setThreadNamePrefix(schedName + "_Worker");
}
tp.initialize();
rsrcs.setJobStore(js);
schedCtxt = new SchedulingContext();
schedCtxt.setInstanceId(rsrcs.getInstanceId());
qs = new QuartzScheduler(rsrcs, schedCtxt, idleWaitTime, dbFailureRetry);
// if(usingJSCMT)
// qs.setSignalOnSchedulingChange(false); // TODO: fixed? (don't need
// this any more?)
// Create Scheduler ref...
Scheduler scheduler = instantiate(rsrcs, qs);
// set job factory if specified
if(jobFactory != null) {
qs.setJobFactory(jobFactory);
}
// add plugins
for (int i = 0; i < plugins.length; i++) {
plugins[i].initialize(pluginNames[i], scheduler);
qs.addSchedulerPlugin(plugins[i]);
}
// add listeners
for (int i = 0; i < jobListeners.length; i++) {
qs.addGlobalJobListener(jobListeners[i]);
}
for (int i = 0; i < triggerListeners.length; i++) {
qs.addGlobalTriggerListener(triggerListeners[i]);
}
// set scheduler context data...
Iterator itr = schedCtxtProps.keySet().iterator();
while(itr.hasNext()) {
String key = (String) itr.next();
String val = schedCtxtProps.getProperty(key);
scheduler.getContext().put(key, val);
}
// fire up job store, and runshell factory
js.initialize(loadHelper, qs.getSchedulerSignaler());
jrsf.initialize(scheduler, schedCtxt);
getLog().info(
"Quartz scheduler '" + scheduler.getSchedulerName()
+ "' initialized from " + propSrc);
getLog().info("Quartz scheduler version: " + qs.getVersion());
// prevents the repository from being garbage collected
qs.addNoGCObject(schedRep);
// prevents the db manager from being garbage collected
if (dbMgr != null) {
qs.addNoGCObject(dbMgr);
}
schedRep.bind(scheduler);
return scheduler;
}
protected Scheduler instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs) {
SchedulingContext schedCtxt = new SchedulingContext();
schedCtxt.setInstanceId(rsrcs.getInstanceId());
Scheduler scheduler = new StdScheduler(qs, schedCtxt);
return scheduler;
}
private void setBeanProps(Object obj, Properties props)
throws NoSuchMethodException, IllegalAccessException,
java.lang.reflect.InvocationTargetException,
IntrospectionException, SchedulerConfigException {
props.remove("class");
BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propDescs = bi.getPropertyDescriptors();
PropertiesParser pp = new PropertiesParser(props);
java.util.Enumeration keys = props.keys();
while (keys.hasMoreElements()) {
String name = (String) keys.nextElement();
String c = name.substring(0, 1).toUpperCase(Locale.US);
String methName = "set" + c + name.substring(1);
java.lang.reflect.Method setMeth = getSetMethod(methName, propDescs);
try {
if (setMeth == null) {
throw new NoSuchMethodException(
"No setter for property '" + name + "'");
}
Class[] params = setMeth.getParameterTypes();
if (params.length != 1) {
throw new NoSuchMethodException(
"No 1-argument setter for property '" + name + "'");
}
if (params[0].equals(int.class)) {
setMeth.invoke(obj, new Object[]{new Integer(pp
.getIntProperty(name))});
} else if (params[0].equals(long.class)) {
setMeth.invoke(obj, new Object[]{new Long(pp
.getLongProperty(name))});
} else if (params[0].equals(float.class)) {
setMeth.invoke(obj, new Object[]{new Float(pp
.getFloatProperty(name))});
} else if (params[0].equals(double.class)) {
setMeth.invoke(obj, new Object[]{new Double(pp
.getDoubleProperty(name))});
} else if (params[0].equals(boolean.class)) {
setMeth.invoke(obj, new Object[]{new Boolean(pp
.getBooleanProperty(name))});
} else if (params[0].equals(String.class)) {
setMeth.invoke(obj,
new Object[]{pp.getStringProperty(name)});
} else {
throw new NoSuchMethodException(
"No primitive-type setter for property '" + name
+ "'");
}
} catch (NumberFormatException nfe) {
throw new SchedulerConfigException("Could not parse property '"
+ name + "' into correct data type: " + nfe.toString());
}
}
}
private java.lang.reflect.Method getSetMethod(String name,
PropertyDescriptor[] props) {
for (int i = 0; i < props.length; i++) {
java.lang.reflect.Method wMeth = props[i].getWriteMethod();
if (wMeth != null && wMeth.getName().equals(name)) {
return wMeth;
}
}
return null;
}
private Class loadClass(String className) throws ClassNotFoundException {
try {
return Thread.currentThread().getContextClassLoader().loadClass(
className);
} catch (ClassNotFoundException e) {
return getClass().getClassLoader().loadClass(className);
}
}
private String getSchedulerName() {
return cfg.getStringProperty(PROP_SCHED_INSTANCE_NAME,
"QuartzScheduler");
}
private String getSchedulerInstId() {
return cfg.getStringProperty(PROP_SCHED_INSTANCE_ID,
DEFAULT_INSTANCE_ID);
}
/**
* <p>
* Returns a handle to the Scheduler produced by this factory.
* </p>
*
* <p>
* If one of the <code>initialize</code> methods has not be previously
* called, then the default (no-arg) <code>initialize()</code> method
* will be called by this method.
* </p>
*/
public Scheduler getScheduler() throws SchedulerException {
if (cfg == null) {
initialize();
}
SchedulerRepository schedRep = SchedulerRepository.getInstance();
Scheduler sched = schedRep.lookup(getSchedulerName());
if (sched != null) {
if (sched.isShutdown()) {
schedRep.remove(getSchedulerName());
} else {
return sched;
}
}
sched = instantiate();
return sched;
}
/**
* <p>
* Returns a handle to the default Scheduler, creating it if it does not
* yet exist.
* </p>
*
* @see #initialize()
*/
public static Scheduler getDefaultScheduler() throws SchedulerException {
StdSchedulerFactory fact = new StdSchedulerFactory();
return fact.getScheduler();
}
/**
* <p>
* Returns a handle to the Scheduler with the given name, if it exists (if
* it has already been instantiated).
* </p>
*/
public Scheduler getScheduler(String schedName) throws SchedulerException {
return SchedulerRepository.getInstance().lookup(schedName);
}
/**
* <p>
* Returns a handle to all known Schedulers (made by any
* StdSchedulerFactory instance.).
* </p>
*/
public Collection getAllSchedulers() throws SchedulerException {
return SchedulerRepository.getInstance().lookupAll();
}
}
| src/java/org/quartz/impl/StdSchedulerFactory.java | /*
* Copyright 2004-2005 OpenSymphony
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
/*
* Previously Copyright (c) 2001-2004 James House
*/
package org.quartz.impl;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.AccessControlException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerConfigException;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerListener;
import org.quartz.core.JobRunShellFactory;
import org.quartz.core.QuartzScheduler;
import org.quartz.core.QuartzSchedulerResources;
import org.quartz.core.SchedulingContext;
import org.quartz.ee.jta.JTAJobRunShellFactory;
import org.quartz.ee.jta.UserTransactionHelper;
import org.quartz.impl.jdbcjobstore.JobStoreSupport;
import org.quartz.simpl.RAMJobStore;
import org.quartz.simpl.SimpleThreadPool;
import org.quartz.spi.ClassLoadHelper;
import org.quartz.spi.InstanceIdGenerator;
import org.quartz.spi.JobFactory;
import org.quartz.spi.JobStore;
import org.quartz.spi.SchedulerPlugin;
import org.quartz.spi.ThreadPool;
import org.quartz.utils.ConnectionProvider;
import org.quartz.utils.DBConnectionManager;
import org.quartz.utils.JNDIConnectionProvider;
import org.quartz.utils.PoolingConnectionProvider;
import org.quartz.utils.PropertiesParser;
/**
* <p>
* An implementation of <code>{@link org.quartz.SchedulerFactory}</code> that
* does all of its work of creating a <code>QuartzScheduler</code> instance
* based on the contenents of a <code>Properties</code> file.
* </p>
*
* <p>
* By default a properties file named "quartz.properties" is loaded from the
* 'current working directory'. If that fails, then the "quartz.properties"
* file located (as a resource) in the org/quartz package is loaded. If you
* wish to use a file other than these defaults, you must define the system
* property 'org.quartz.properties' to point to the file you want.
* </p>
*
* <p>
* See the sample properties files that are distributed with Quartz for
* information about the various settings available within the file.
* </p>
*
* <p>
* Alternatively, you can explicitly initialize the factory by calling one of
* the <code>initialize(xx)</code> methods before calling <code>getScheduler()</code>.
* </p>
*
* <p>
* Instances of the specified <code>{@link org.quartz.spi.JobStore}</code>,
* <code>{@link org.quartz.spi.ThreadPool}</code>, classes will be created
* by name, and then any additional properties specified for them in the config
* file will be set on the instance by calling an equivalent 'set' method. For
* example if the properties file contains the property
* 'org.quartz.jobStore.myProp = 10' then after the JobStore class has been
* instantiated, the method 'setMyProp()' will be called on it. Type conversion
* to primitive Java types (int, long, float, double, boolean, and String) are
* performed before calling the property's setter method.
* </p>
*
* @author James House
* @author Anthony Eden
* @author Mohammad Rezaei
*/
public class StdSchedulerFactory implements SchedulerFactory {
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Constants.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
public static final String PROPERTIES_FILE = "org.quartz.properties";
public static final String PROP_SCHED_INSTANCE_NAME = "org.quartz.scheduler.instanceName";
public static final String PROP_SCHED_INSTANCE_ID = "org.quartz.scheduler.instanceId";
public static final String PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS = "org.quartz.scheduler.instanceIdGenerator.class";
public static final String PROP_SCHED_THREAD_NAME = "org.quartz.scheduler.threadName";
public static final String PROP_SCHED_RMI_EXPORT = "org.quartz.scheduler.rmi.export";
public static final String PROP_SCHED_RMI_PROXY = "org.quartz.scheduler.rmi.proxy";
public static final String PROP_SCHED_RMI_HOST = "org.quartz.scheduler.rmi.registryHost";
public static final String PROP_SCHED_RMI_PORT = "org.quartz.scheduler.rmi.registryPort";
public static final String PROP_SCHED_RMI_SERVER_PORT = "org.quartz.scheduler.rmi.serverPort";
public static final String PROP_SCHED_RMI_CREATE_REGISTRY = "org.quartz.scheduler.rmi.createRegistry";
public static final String PROP_SCHED_WRAP_JOB_IN_USER_TX = "org.quartz.scheduler.wrapJobExecutionInUserTransaction";
public static final String PROP_SCHED_USER_TX_URL = "org.quartz.scheduler.userTransactionURL";
public static final String PROP_SCHED_IDLE_WAIT_TIME = "org.quartz.scheduler.idleWaitTime";
public static final String PROP_SCHED_DB_FAILURE_RETRY_INTERVAL = "org.quartz.scheduler.dbFailureRetryInterval";
public static final String PROP_SCHED_CLASS_LOAD_HELPER_CLASS = "org.quartz.scheduler.classLoadHelper.class";
public static final String PROP_SCHED_JOB_FACTORY_CLASS = "org.quartz.scheduler.jobFactory.class";
public static final String PROP_SCHED_JOB_FACTORY_PREFIX = "org.quartz.scheduler.jobFactory";
public static final String PROP_SCHED_CONTEXT_PREFIX = "org.quartz.context.key";
public static final String PROP_THREAD_POOL_PREFIX = "org.quartz.threadPool";
public static final String PROP_THREAD_POOL_CLASS = "org.quartz.threadPool.class";
public static final String PROP_JOB_STORE_PREFIX = "org.quartz.jobStore";
public static final String PROP_JOB_STORE_CLASS = "org.quartz.jobStore.class";
public static final String PROP_JOB_STORE_USE_PROP = "org.quartz.jobStore.useProperties";
public static final String PROP_DATASOURCE_PREFIX = "org.quartz.dataSource";
public static final String PROP_CONNECTION_PROVIDER_CLASS = "connectionProvider.class";
public static final String PROP_DATASOURCE_DRIVER = "driver";
public static final String PROP_DATASOURCE_URL = "URL";
public static final String PROP_DATASOURCE_USER = "user";
public static final String PROP_DATASOURCE_PASSWORD = "password";
public static final String PROP_DATASOURCE_MAX_CONNECTIONS = "maxConnections";
public static final String PROP_DATASOURCE_VALIDATION_QUERY = "validationQuery";
public static final String PROP_DATASOURCE_JNDI_URL = "jndiURL";
public static final String PROP_DATASOURCE_JNDI_ALWAYS_LOOKUP = "jndiAlwaysLookup";
public static final String PROP_DATASOURCE_JNDI_INITIAL = "java.naming.factory.initial";
public static final String PROP_DATASOURCE_JNDI_PROVDER = "java.naming.provider.url";
public static final String PROP_DATASOURCE_JNDI_PRINCIPAL = "java.naming.security.principal";
public static final String PROP_DATASOURCE_JNDI_CREDENTIALS = "java.naming.security.credentials";
public static final String PROP_PLUGIN_PREFIX = "org.quartz.plugin";
public static final String PROP_PLUGIN_CLASS = "class";
public static final String PROP_JOB_LISTENER_PREFIX = "org.quartz.jobListener";
public static final String PROP_TRIGGER_LISTENER_PREFIX = "org.quartz.triggerListener";
public static final String PROP_LISTENER_CLASS = "class";
public static final String DEFAULT_INSTANCE_ID = "NON_CLUSTERED";
public static final String AUTO_GENERATE_INSTANCE_ID = "AUTO";
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Data members.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
private SchedulerException initException = null;
private String propSrc = null;
private PropertiesParser cfg;
private final Log log = LogFactory.getLog(getClass());
// private Scheduler scheduler;
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Constructors.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* Create an uninitialized StdSchedulerFactory.
*/
public StdSchedulerFactory() {
}
/**
* Create a StdSchedulerFactory that has been initialized via
* <code>{@link #initialize(Properties)}</code>.
*
* @see #initialize(Properties)
*/
public StdSchedulerFactory(Properties props) throws SchedulerException {
initialize(props);
}
/**
* Create a StdSchedulerFactory that has been initialized via
* <code>{@link #initialize(String)}</code>.
*
* @see #initialize(String)
*/
public StdSchedulerFactory(String fileName) throws SchedulerException {
initialize(fileName);
}
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Interface.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
public Log getLog() {
return log;
}
/**
* <p>
* Initialize the <code>{@link org.quartz.SchedulerFactory}</code> with
* the contents of a <code>Properties</code> file and overriding System
* properties.
* </p>
*
* <p>
* By default a properties file named "quartz.properties" is loaded from
* the 'current working directory'. If that fails, then the
* "quartz.properties" file located (as a resource) in the org/quartz
* package is loaded. If you wish to use a file other than these defaults,
* you must define the system property 'org.quartz.properties' to point to
* the file you want.
* </p>
*
* <p>
* System properties (environment variables, and -D definitions on the
* command-line when running the JVM) override any properties in the
* loaded file. For this reason, you may want to use a different initialize()
* method if your application security policy prohibits access to
* <code>{@link java.lang.System#getProperties()}</code>.
* </p>
*/
public void initialize() throws SchedulerException {
// short-circuit if already initialized
if (cfg != null) {
return;
}
if (initException != null) {
throw initException;
}
String requestedFile = System.getProperty(PROPERTIES_FILE);
String propFileName = requestedFile != null ? requestedFile
: "quartz.properties";
File propFile = new File(propFileName);
Properties props = new Properties();
if (propFile.exists()) {
try {
if (requestedFile != null) {
propSrc = "specified file: '" + requestedFile + "'";
} else {
propSrc = "default file in current working dir: 'quartz.properties'";
}
props.load(new BufferedInputStream(new FileInputStream(
propFileName)));
} catch (IOException ioe) {
initException = new SchedulerException("Properties file: '"
+ propFileName + "' could not be read.", ioe);
throw initException;
}
} else if (requestedFile != null) {
InputStream in =
Thread.currentThread().getContextClassLoader().getResourceAsStream(requestedFile);
if(in == null) {
initException = new SchedulerException("Properties file: '"
+ requestedFile + "' could not be found.");
throw initException;
}
propSrc = "specified file: '" + requestedFile + "' in the class resource path.";
try {
props.load(new BufferedInputStream(in));
} catch (IOException ioe) {
initException = new SchedulerException("Properties file: '"
+ requestedFile + "' could not be read.", ioe);
throw initException;
}
} else {
propSrc = "default resource file in Quartz package: 'quartz.properties'";
InputStream in = getClass().getClassLoader().getResourceAsStream(
"quartz.properties");
if (in == null) {
in = getClass().getClassLoader().getResourceAsStream(
"/quartz.properties");
}
if (in == null) {
in = getClass().getClassLoader().getResourceAsStream(
"org/quartz/quartz.properties");
}
if (in == null) {
initException = new SchedulerException(
"Default quartz.properties not found in class path");
throw initException;
}
try {
props.load(in);
} catch (IOException ioe) {
initException = new SchedulerException(
"Resource properties file: 'org/quartz/quartz.properties' "
+ "could not be read from the classpath.", ioe);
throw initException;
}
}
initialize(overrideWithSysProps(props));
}
/**
* Add all System properties to the given <code>props</code>. Will override
* any properties that already exist in the given <code>props</code>.
*/
private Properties overrideWithSysProps(Properties props) {
Properties sysProps = null;
try {
sysProps = System.getProperties();
} catch (AccessControlException e) {
getLog().warn(
"Skipping overriding quartz properties with System properties " +
"during initialization because of an AccessControlException. " +
"This is likely due to not having read/write access for " +
"java.util.PropertyPermission as required by java.lang.System.getProperties(). " +
"To resolve this warning, either add this permission to your policy file or " +
"use a non-default version of initialize().",
e);
}
if (sysProps != null) {
props.putAll(sysProps);
}
return props;
}
/**
* <p>
* Initialize the <code>{@link org.quartz.SchedulerFactory}</code> with
* the contenents of the <code>Properties</code> file with the given
* name.
* </p>
*/
public void initialize(String filename) throws SchedulerException {
// short-circuit if already initialized
if (cfg != null) {
return;
}
if (initException != null) {
throw initException;
}
InputStream is = null;
Properties props = new Properties();
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
try {
if(is != null) {
is = new BufferedInputStream(is);
propSrc = "the specified file : '" + filename + "' from the class resource path.";
} else {
is = new BufferedInputStream(new FileInputStream(filename));
propSrc = "the specified file : '" + filename + "'";
}
props.load(is);
} catch (IOException ioe) {
initException = new SchedulerException("Properties file: '"
+ filename + "' could not be read.", ioe);
throw initException;
}
initialize(props);
}
/**
* <p>
* Initialize the <code>{@link org.quartz.SchedulerFactory}</code> with
* the contenents of the <code>Properties</code> file opened with the
* given <code>InputStream</code>.
* </p>
*/
public void initialize(InputStream propertiesStream)
throws SchedulerException {
// short-circuit if already initialized
if (cfg != null) {
return;
}
if (initException != null) {
throw initException;
}
Properties props = new Properties();
if (propertiesStream != null) {
try {
props.load(propertiesStream);
propSrc = "an externally opened InputStream.";
} catch (IOException e) {
initException = new SchedulerException(
"Error loading property data from InputStream", e);
throw initException;
}
} else {
initException = new SchedulerException(
"Error loading property data from InputStream - InputStream is null.");
throw initException;
}
initialize(props);
}
/**
* <p>
* Initialize the <code>{@link org.quartz.SchedulerFactory}</code> with
* the contenents of the given <code>Properties</code> object.
* </p>
*/
public void initialize(Properties props) throws SchedulerException {
if (propSrc == null) {
propSrc = "an externally provided properties instance.";
}
this.cfg = new PropertiesParser(props);
}
private Scheduler instantiate() throws SchedulerException {
if (cfg == null) {
initialize();
}
if (initException != null) {
throw initException;
}
JobStore js = null;
ThreadPool tp = null;
QuartzScheduler qs = null;
SchedulingContext schedCtxt = null;
DBConnectionManager dbMgr = null;
String instanceIdGeneratorClass = null;
Properties tProps = null;
String userTXLocation = null;
boolean wrapJobInTx = false;
boolean autoId = false;
long idleWaitTime = -1;
long dbFailureRetry = -1;
String classLoadHelperClass;
String jobFactoryClass;
SchedulerRepository schedRep = SchedulerRepository.getInstance();
// Get Scheduler Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String schedName = cfg.getStringProperty(PROP_SCHED_INSTANCE_NAME,
"QuartzScheduler");
String threadName = cfg.getStringProperty(PROP_SCHED_THREAD_NAME,
schedName + "_QuartzSchedulerThread");
String schedInstId = cfg.getStringProperty(PROP_SCHED_INSTANCE_ID,
DEFAULT_INSTANCE_ID);
if (schedInstId.equals(AUTO_GENERATE_INSTANCE_ID)) {
autoId = true;
instanceIdGeneratorClass = cfg.getStringProperty(
PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS,
"org.quartz.simpl.SimpleInstanceIdGenerator");
}
userTXLocation = cfg.getStringProperty(PROP_SCHED_USER_TX_URL,
userTXLocation);
if (userTXLocation != null && userTXLocation.trim().length() == 0) {
userTXLocation = null;
}
classLoadHelperClass = cfg.getStringProperty(
PROP_SCHED_CLASS_LOAD_HELPER_CLASS,
"org.quartz.simpl.CascadingClassLoadHelper");
wrapJobInTx = cfg.getBooleanProperty(PROP_SCHED_WRAP_JOB_IN_USER_TX,
wrapJobInTx);
jobFactoryClass = cfg.getStringProperty(
PROP_SCHED_JOB_FACTORY_CLASS, null);
idleWaitTime = cfg.getLongProperty(PROP_SCHED_IDLE_WAIT_TIME,
idleWaitTime);
dbFailureRetry = cfg.getLongProperty(
PROP_SCHED_DB_FAILURE_RETRY_INTERVAL, dbFailureRetry);
boolean rmiExport = cfg
.getBooleanProperty(PROP_SCHED_RMI_EXPORT, false);
boolean rmiProxy = cfg.getBooleanProperty(PROP_SCHED_RMI_PROXY, false);
String rmiHost = cfg
.getStringProperty(PROP_SCHED_RMI_HOST, "localhost");
int rmiPort = cfg.getIntProperty(PROP_SCHED_RMI_PORT, 1099);
int rmiServerPort = cfg.getIntProperty(PROP_SCHED_RMI_SERVER_PORT, -1);
String rmiCreateRegistry = cfg.getStringProperty(
PROP_SCHED_RMI_CREATE_REGISTRY,
QuartzSchedulerResources.CREATE_REGISTRY_NEVER);
Properties schedCtxtProps = cfg.getPropertyGroup(PROP_SCHED_CONTEXT_PREFIX, true);
// If Proxying to remote scheduler, short-circuit here...
// ~~~~~~~~~~~~~~~~~~
if (rmiProxy) {
if (autoId) {
schedInstId = DEFAULT_INSTANCE_ID;
}
schedCtxt = new SchedulingContext();
schedCtxt.setInstanceId(schedInstId);
String uid = QuartzSchedulerResources.getUniqueIdentifier(
schedName, schedInstId);
RemoteScheduler remoteScheduler = new RemoteScheduler(schedCtxt,
uid, rmiHost, rmiPort);
schedRep.bind(remoteScheduler);
return remoteScheduler;
}
// Create class load helper
ClassLoadHelper loadHelper = null;
try {
loadHelper = (ClassLoadHelper) loadClass(classLoadHelperClass)
.newInstance();
} catch (Exception e) {
throw new SchedulerConfigException(
"Unable to instantiate class load helper class: "
+ e.getMessage(), e);
}
loadHelper.initialize();
JobFactory jobFactory = null;
if(jobFactoryClass != null) {
try {
jobFactory = (JobFactory) loadHelper.loadClass(jobFactoryClass)
.newInstance();
} catch (Exception e) {
throw new SchedulerConfigException(
"Unable to instantiate JobFactory class: "
+ e.getMessage(), e);
}
tProps = cfg.getPropertyGroup(PROP_SCHED_JOB_FACTORY_PREFIX, true);
try {
setBeanProps(jobFactory, tProps);
} catch (Exception e) {
initException = new SchedulerException("JobFactory class '"
+ jobFactoryClass + "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
}
InstanceIdGenerator instanceIdGenerator = null;
if(instanceIdGeneratorClass != null) {
try {
instanceIdGenerator = (InstanceIdGenerator) loadHelper.loadClass(instanceIdGeneratorClass)
.newInstance();
} catch (Exception e) {
throw new SchedulerConfigException(
"Unable to instantiate InstanceIdGenerator class: "
+ e.getMessage(), e);
}
}
// Get ThreadPool Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String tpClass = cfg.getStringProperty(PROP_THREAD_POOL_CLASS, null);
if (tpClass == null) {
initException = new SchedulerException(
"ThreadPool class not specified. ",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
tp = (ThreadPool) loadHelper.loadClass(tpClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException("ThreadPool class '"
+ tpClass + "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
tProps = cfg.getPropertyGroup(PROP_THREAD_POOL_PREFIX, true);
try {
setBeanProps(tp, tProps);
} catch (Exception e) {
initException = new SchedulerException("ThreadPool class '"
+ tpClass + "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
// Get JobStore Properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String jsClass = cfg.getStringProperty(PROP_JOB_STORE_CLASS,
RAMJobStore.class.getName());
if (jsClass == null) {
initException = new SchedulerException(
"JobStore class not specified. ",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
js = (JobStore) loadHelper.loadClass(jsClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException("JobStore class '" + jsClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
tProps = cfg.getPropertyGroup(PROP_JOB_STORE_PREFIX, true);
try {
setBeanProps(js, tProps);
} catch (Exception e) {
initException = new SchedulerException("JobStore class '" + jsClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
if (js instanceof org.quartz.impl.jdbcjobstore.JobStoreSupport) {
((org.quartz.impl.jdbcjobstore.JobStoreSupport) js)
.setInstanceId(schedInstId);
((org.quartz.impl.jdbcjobstore.JobStoreSupport) js)
.setInstanceName(schedName);
}
// Set up any DataSources
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String[] dsNames = cfg.getPropertyGroups(PROP_DATASOURCE_PREFIX);
for (int i = 0; i < dsNames.length; i++) {
PropertiesParser pp = new PropertiesParser(cfg.getPropertyGroup(
PROP_DATASOURCE_PREFIX + "." + dsNames[i], true));
String cpClass = pp.getStringProperty(PROP_CONNECTION_PROVIDER_CLASS, null);
// custom connectionProvider...
if(cpClass != null) {
ConnectionProvider cp = null;
try {
cp = (ConnectionProvider) loadHelper.loadClass(cpClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException("ConnectionProvider class '" + cpClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
// remove the class name, so it isn't attempted to be set
pp.getUnderlyingProperties().remove(
PROP_CONNECTION_PROVIDER_CLASS);
setBeanProps(cp, pp.getUnderlyingProperties());
} catch (Exception e) {
initException = new SchedulerException("ConnectionProvider class '" + cpClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
dbMgr = DBConnectionManager.getInstance();
dbMgr.addConnectionProvider(dsNames[i], cp);
} else {
String dsDriver = pp
.getStringProperty(PROP_DATASOURCE_DRIVER, null);
String dsURL = pp.getStringProperty(PROP_DATASOURCE_URL, null);
boolean dsAlwaysLookup = pp.getBooleanProperty(
PROP_DATASOURCE_JNDI_ALWAYS_LOOKUP, false);
String dsUser = pp.getStringProperty(PROP_DATASOURCE_USER, "");
String dsPass = pp.getStringProperty(PROP_DATASOURCE_PASSWORD, "");
int dsCnt = pp.getIntProperty(PROP_DATASOURCE_MAX_CONNECTIONS, 10);
String dsJndi = pp
.getStringProperty(PROP_DATASOURCE_JNDI_URL, null);
String dsJndiInitial = pp.getStringProperty(
PROP_DATASOURCE_JNDI_INITIAL, null);
String dsJndiProvider = pp.getStringProperty(
PROP_DATASOURCE_JNDI_PROVDER, null);
String dsJndiPrincipal = pp.getStringProperty(
PROP_DATASOURCE_JNDI_PRINCIPAL, null);
String dsJndiCredentials = pp.getStringProperty(
PROP_DATASOURCE_JNDI_CREDENTIALS, null);
String dsValidation = pp.getStringProperty(
PROP_DATASOURCE_VALIDATION_QUERY, null);
if (dsJndi != null) {
Properties props = null;
if (null != dsJndiInitial || null != dsJndiProvider
|| null != dsJndiPrincipal || null != dsJndiCredentials) {
props = new Properties();
if (dsJndiInitial != null) {
props.put(PROP_DATASOURCE_JNDI_INITIAL,
dsJndiInitial);
}
if (dsJndiProvider != null) {
props.put(PROP_DATASOURCE_JNDI_PROVDER,
dsJndiProvider);
}
if (dsJndiPrincipal != null) {
props.put(PROP_DATASOURCE_JNDI_PRINCIPAL,
dsJndiPrincipal);
}
if (dsJndiCredentials != null) {
props.put(PROP_DATASOURCE_JNDI_CREDENTIALS,
dsJndiCredentials);
}
}
JNDIConnectionProvider cp = new JNDIConnectionProvider(dsJndi,
props, dsAlwaysLookup);
dbMgr = DBConnectionManager.getInstance();
dbMgr.addConnectionProvider(dsNames[i], cp);
} else {
if (dsDriver == null) {
initException = new SchedulerException(
"Driver not specified for DataSource: "
+ dsNames[i]);
throw initException;
}
if (dsURL == null) {
initException = new SchedulerException(
"DB URL not specified for DataSource: "
+ dsNames[i]);
throw initException;
}
try {
PoolingConnectionProvider cp = new PoolingConnectionProvider(
dsDriver, dsURL, dsUser, dsPass, dsCnt,
dsValidation);
dbMgr = DBConnectionManager.getInstance();
dbMgr.addConnectionProvider(dsNames[i], cp);
} catch (SQLException sqle) {
initException = new SchedulerException(
"Could not initialize DataSource: " + dsNames[i],
sqle);
throw initException;
}
}
}
}
// Set up any SchedulerPlugins
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String[] pluginNames = cfg.getPropertyGroups(PROP_PLUGIN_PREFIX);
SchedulerPlugin[] plugins = new SchedulerPlugin[pluginNames.length];
for (int i = 0; i < pluginNames.length; i++) {
Properties pp = cfg.getPropertyGroup(PROP_PLUGIN_PREFIX + "."
+ pluginNames[i], true);
String plugInClass = pp.getProperty(PROP_PLUGIN_CLASS, null);
if (plugInClass == null) {
initException = new SchedulerException(
"SchedulerPlugin class not specified for plugin '"
+ pluginNames[i] + "'",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
SchedulerPlugin plugin = null;
try {
plugin = (SchedulerPlugin)
loadHelper.loadClass(plugInClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException(
"SchedulerPlugin class '" + plugInClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
setBeanProps(plugin, pp);
} catch (Exception e) {
initException = new SchedulerException(
"JobStore SchedulerPlugin '" + plugInClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
plugins[i] = plugin;
}
// Set up any JobListeners
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class[] strArg = new Class[] { String.class };
String[] jobListenerNames = cfg.getPropertyGroups(PROP_JOB_LISTENER_PREFIX);
JobListener[] jobListeners = new JobListener[jobListenerNames.length];
for (int i = 0; i < jobListenerNames.length; i++) {
Properties lp = cfg.getPropertyGroup(PROP_JOB_LISTENER_PREFIX + "."
+ jobListenerNames[i], true);
String listenerClass = lp.getProperty(PROP_LISTENER_CLASS, null);
if (listenerClass == null) {
initException = new SchedulerException(
"JobListener class not specified for listener '"
+ jobListenerNames[i] + "'",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
JobListener listener = null;
try {
listener = (JobListener)
loadHelper.loadClass(listenerClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException(
"JobListener class '" + listenerClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
Method nameSetter = listener.getClass().getMethod("setName", strArg);
if(nameSetter != null) {
nameSetter.invoke(listener, new Object[] {jobListenerNames[i] } );
}
setBeanProps(listener, lp);
} catch (Exception e) {
initException = new SchedulerException(
"JobListener '" + listenerClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
jobListeners[i] = listener;
}
// Set up any TriggerListeners
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String[] triggerListenerNames = cfg.getPropertyGroups(PROP_TRIGGER_LISTENER_PREFIX);
TriggerListener[] triggerListeners = new TriggerListener[triggerListenerNames.length];
for (int i = 0; i < triggerListenerNames.length; i++) {
Properties lp = cfg.getPropertyGroup(PROP_TRIGGER_LISTENER_PREFIX + "."
+ triggerListenerNames[i], true);
String listenerClass = lp.getProperty(PROP_LISTENER_CLASS, null);
if (listenerClass == null) {
initException = new SchedulerException(
"TriggerListener class not specified for listener '"
+ triggerListenerNames[i] + "'",
SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
TriggerListener listener = null;
try {
listener = (TriggerListener)
loadHelper.loadClass(listenerClass).newInstance();
} catch (Exception e) {
initException = new SchedulerException(
"TriggerListener class '" + listenerClass
+ "' could not be instantiated.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
try {
Method nameSetter = listener.getClass().getMethod("setName", strArg);
if(nameSetter != null) {
nameSetter.invoke(listener, new Object[] {triggerListenerNames[i] } );
}
setBeanProps(listener, lp);
} catch (Exception e) {
initException = new SchedulerException(
"TriggerListener '" + listenerClass
+ "' props could not be configured.", e);
initException
.setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
throw initException;
}
triggerListeners[i] = listener;
}
// Fire everything up
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
JobRunShellFactory jrsf = null; // Create correct run-shell factory...
UserTransactionHelper.setUserTxLocation(userTXLocation);
if (wrapJobInTx) {
jrsf = new JTAJobRunShellFactory();
} else {
jrsf = new StdJobRunShellFactory();
}
if (autoId) {
try {
schedInstId = DEFAULT_INSTANCE_ID;
if (js instanceof org.quartz.impl.jdbcjobstore.JobStoreSupport) {
if(((org.quartz.impl.jdbcjobstore.JobStoreSupport) js)
.isClustered()) {
schedInstId = instanceIdGenerator.generateInstanceId();
}
}
} catch (Exception e) {
getLog().error("Couldn't generate instance Id!", e);
throw new IllegalStateException(
"Cannot run without an instance id.");
}
}
if (js instanceof JobStoreSupport) {
JobStoreSupport jjs = (JobStoreSupport) js;
jjs.setInstanceId(schedInstId);
jjs.setDbRetryInterval(dbFailureRetry);
}
QuartzSchedulerResources rsrcs = new QuartzSchedulerResources();
rsrcs.setName(schedName);
rsrcs.setThreadName(threadName);
rsrcs.setInstanceId(schedInstId);
rsrcs.setJobRunShellFactory(jrsf);
if (rmiExport) {
rsrcs.setRMIRegistryHost(rmiHost);
rsrcs.setRMIRegistryPort(rmiPort);
rsrcs.setRMIServerPort(rmiServerPort);
rsrcs.setRMICreateRegistryStrategy(rmiCreateRegistry);
}
rsrcs.setThreadPool(tp);
if(tp instanceof SimpleThreadPool) {
((SimpleThreadPool)tp).setThreadNamePrefix(schedName + "_Worker");
}
tp.initialize();
rsrcs.setJobStore(js);
schedCtxt = new SchedulingContext();
schedCtxt.setInstanceId(rsrcs.getInstanceId());
qs = new QuartzScheduler(rsrcs, schedCtxt, idleWaitTime, dbFailureRetry);
// if(usingJSCMT)
// qs.setSignalOnSchedulingChange(false); // TODO: fixed? (don't need
// this any more?)
// Create Scheduler ref...
Scheduler scheduler = instantiate(rsrcs, qs);
// set job factory if specified
if(jobFactory != null) {
qs.setJobFactory(jobFactory);
}
// add plugins
for (int i = 0; i < plugins.length; i++) {
plugins[i].initialize(pluginNames[i], scheduler);
qs.addSchedulerPlugin(plugins[i]);
}
// add listeners
for (int i = 0; i < jobListeners.length; i++) {
qs.addGlobalJobListener(jobListeners[i]);
}
for (int i = 0; i < triggerListeners.length; i++) {
qs.addGlobalTriggerListener(triggerListeners[i]);
}
// set scheduler context data...
Iterator itr = schedCtxtProps.keySet().iterator();
while(itr.hasNext()) {
String key = (String) itr.next();
String val = schedCtxtProps.getProperty(key);
scheduler.getContext().put(key, val);
}
// fire up job store, and runshell factory
js.initialize(loadHelper, qs.getSchedulerSignaler());
jrsf.initialize(scheduler, schedCtxt);
getLog().info(
"Quartz scheduler '" + scheduler.getSchedulerName()
+ "' initialized from " + propSrc);
getLog().info("Quartz scheduler version: " + qs.getVersion());
// prevents the repository from being garbage collected
qs.addNoGCObject(schedRep);
// prevents the db manager from being garbage collected
if (dbMgr != null) {
qs.addNoGCObject(dbMgr);
}
schedRep.bind(scheduler);
return scheduler;
}
protected Scheduler instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs) {
SchedulingContext schedCtxt = new SchedulingContext();
schedCtxt.setInstanceId(rsrcs.getInstanceId());
Scheduler scheduler = new StdScheduler(qs, schedCtxt);
return scheduler;
}
private void setBeanProps(Object obj, Properties props)
throws NoSuchMethodException, IllegalAccessException,
java.lang.reflect.InvocationTargetException,
IntrospectionException, SchedulerConfigException {
props.remove("class");
BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propDescs = bi.getPropertyDescriptors();
PropertiesParser pp = new PropertiesParser(props);
java.util.Enumeration keys = props.keys();
while (keys.hasMoreElements()) {
String name = (String) keys.nextElement();
String c = name.substring(0, 1).toUpperCase(Locale.US);
String methName = "set" + c + name.substring(1);
java.lang.reflect.Method setMeth = getSetMethod(methName, propDescs);
try {
if (setMeth == null) {
throw new NoSuchMethodException(
"No setter for property '" + name + "'");
}
Class[] params = setMeth.getParameterTypes();
if (params.length != 1) {
throw new NoSuchMethodException(
"No 1-argument setter for property '" + name + "'");
}
if (params[0].equals(int.class)) {
setMeth.invoke(obj, new Object[]{new Integer(pp
.getIntProperty(name))});
} else if (params[0].equals(long.class)) {
setMeth.invoke(obj, new Object[]{new Long(pp
.getLongProperty(name))});
} else if (params[0].equals(float.class)) {
setMeth.invoke(obj, new Object[]{new Float(pp
.getFloatProperty(name))});
} else if (params[0].equals(double.class)) {
setMeth.invoke(obj, new Object[]{new Double(pp
.getDoubleProperty(name))});
} else if (params[0].equals(boolean.class)) {
setMeth.invoke(obj, new Object[]{new Boolean(pp
.getBooleanProperty(name))});
} else if (params[0].equals(String.class)) {
setMeth.invoke(obj,
new Object[]{pp.getStringProperty(name)});
} else {
throw new NoSuchMethodException(
"No primitive-type setter for property '" + name
+ "'");
}
} catch (NumberFormatException nfe) {
throw new SchedulerConfigException("Could not parse property '"
+ name + "' into correct data type: " + nfe.toString());
}
}
}
private java.lang.reflect.Method getSetMethod(String name,
PropertyDescriptor[] props) {
for (int i = 0; i < props.length; i++) {
java.lang.reflect.Method wMeth = props[i].getWriteMethod();
if (wMeth != null && wMeth.getName().equals(name)) {
return wMeth;
}
}
return null;
}
private Class loadClass(String className) throws ClassNotFoundException {
try {
return Thread.currentThread().getContextClassLoader().loadClass(
className);
} catch (ClassNotFoundException e) {
return getClass().getClassLoader().loadClass(className);
}
}
private String getSchedulerName() {
return cfg.getStringProperty(PROP_SCHED_INSTANCE_NAME,
"QuartzScheduler");
}
private String getSchedulerInstId() {
return cfg.getStringProperty(PROP_SCHED_INSTANCE_ID,
DEFAULT_INSTANCE_ID);
}
/**
* <p>
* Returns a handle to the Scheduler produced by this factory.
* </p>
*
* <p>
* If one of the <code>initialize</code> methods has not be previously
* called, then the default (no-arg) <code>initialize()</code> method
* will be called by this method.
* </p>
*/
public Scheduler getScheduler() throws SchedulerException {
if (cfg == null) {
initialize();
}
SchedulerRepository schedRep = SchedulerRepository.getInstance();
Scheduler sched = schedRep.lookup(getSchedulerName());
if (sched != null) {
if (sched.isShutdown()) {
schedRep.remove(getSchedulerName());
} else {
return sched;
}
}
sched = instantiate();
return sched;
}
/**
* <p>
* Returns a handle to the default Scheduler, creating it if it does not
* yet exist.
* </p>
*
* @see #initialize()
*/
public static Scheduler getDefaultScheduler() throws SchedulerException {
StdSchedulerFactory fact = new StdSchedulerFactory();
return fact.getScheduler();
}
/**
* <p>
* Returns a handle to the Scheduler with the given name, if it exists (if
* it has already been instantiated).
* </p>
*/
public Scheduler getScheduler(String schedName) throws SchedulerException {
return SchedulerRepository.getInstance().lookup(schedName);
}
/**
* <p>
* Returns a handle to all known Schedulers (made by any
* StdSchedulerFactory instance.).
* </p>
*/
public Collection getAllSchedulers() throws SchedulerException {
return SchedulerRepository.getInstance().lookupAll();
}
}
| Issue number: QUARTZ-429
Support setting properties on the InstanceIdGenerator
| src/java/org/quartz/impl/StdSchedulerFactory.java | Issue number: QUARTZ-429 Support setting properties on the InstanceIdGenerator | <ide><path>rc/java/org/quartz/impl/StdSchedulerFactory.java
<ide>
<ide> public static final String PROP_SCHED_INSTANCE_ID = "org.quartz.scheduler.instanceId";
<ide>
<del> public static final String PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS = "org.quartz.scheduler.instanceIdGenerator.class";
<add> public static final String PROP_SCHED_INSTANCE_ID_GENERATOR_PREFIX = "org.quartz.scheduler.instanceIdGenerator";
<add>
<add> public static final String PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS =
<add> PROP_SCHED_INSTANCE_ID_GENERATOR_PREFIX + ".class";
<ide>
<ide> public static final String PROP_SCHED_THREAD_NAME = "org.quartz.scheduler.threadName";
<ide>
<ide> + e.getMessage(), e);
<ide> }
<ide> }
<del>
<add> tProps = cfg.getPropertyGroup(PROP_SCHED_INSTANCE_ID_GENERATOR_PREFIX, true);
<add> try {
<add> setBeanProps(instanceIdGenerator, tProps);
<add> } catch (Exception e) {
<add> initException = new SchedulerException("InstanceIdGenerator class '"
<add> + instanceIdGeneratorClass + "' props could not be configured.", e);
<add> initException
<add> .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION);
<add> throw initException;
<add> }
<add>
<ide> // Get ThreadPool Properties
<ide> // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<ide> |
|
Java | apache-2.0 | 8903f448f30a3b1146b92408e5c8258ba2d2c1f7 | 0 | apache/portals-pluto,apache/portals-pluto,apache/portals-pluto | package org.apache.pluto.internal.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Configuration {
private static final Log LOG =
LogFactory.getLog(Configuration.class);
public static final ResourceBundle BUNDLE =
PropertyResourceBundle.getBundle("org.apache.pluto.core.pluto-configuration");
private static final String CONTAINER_RUNTIME_OPTIONS =
"org.apache.pluto.container.supportedContainerRuntimeOptions";
/**
* org.apache.pluto.PREVENT_UNECESSARY_CROSS_CONTEXT
*/
private static final String PREVENT_UNECESSARY_CROSS_CONTEXT =
"org.apache.pluto.PREVENT_UNECESSARY_CROSS_CONTEXT";
public static List<String> getSupportedContainerRuntimeOptions() {
String options = BUNDLE.getString(CONTAINER_RUNTIME_OPTIONS);
List<String> result = new ArrayList<String>();
String[] s = options.split(",");
for (String string : s) {
result.add(string);
}
return result;
}
private static Boolean prevent;
public static boolean preventUnecessaryCrossContext() {
if (prevent == null) {
try {
String test = BUNDLE.getString(PREVENT_UNECESSARY_CROSS_CONTEXT);
prevent = new Boolean(test);
} catch (MissingResourceException mre) {
prevent = Boolean.FALSE;
}
}
return prevent.booleanValue();
}
}
| pluto-container/src/main/java/org/apache/pluto/internal/impl/Configuration.java | package org.apache.pluto.internal.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Configuration {
private static final Log LOG =
LogFactory.getLog(Configuration.class);
public static final ResourceBundle BUNDLE =
PropertyResourceBundle.getBundle("org.apache.pluto.core.pluto-configuration");
private static final String CONTAINER_RUNTIME_OPTIONS =
"org.apache.pluto.container.supportedContainerRuntimeOptions";
public static List<String> getSupportedContainerRuntimeOptions() {
String options = BUNDLE.getString(CONTAINER_RUNTIME_OPTIONS);
List<String> result = new ArrayList<String>();
String[] s = options.split(",");
for (String string : s) {
result.add(string);
}
return result;
}
}
| Added preventUnecessaryCrossContext() from trunk for PLUTO-488 patch.
git-svn-id: a4614e06ec49ab7329f191e44dd6734879b97a19@678334 13f79535-47bb-0310-9956-ffa450edef68
| pluto-container/src/main/java/org/apache/pluto/internal/impl/Configuration.java | Added preventUnecessaryCrossContext() from trunk for PLUTO-488 patch. | <ide><path>luto-container/src/main/java/org/apache/pluto/internal/impl/Configuration.java
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<add>import java.util.MissingResourceException;
<ide> import java.util.PropertyResourceBundle;
<ide> import java.util.ResourceBundle;
<ide>
<ide>
<ide> private static final String CONTAINER_RUNTIME_OPTIONS =
<ide> "org.apache.pluto.container.supportedContainerRuntimeOptions";
<add>
<add> /**
<add> * org.apache.pluto.PREVENT_UNECESSARY_CROSS_CONTEXT
<add> */
<add> private static final String PREVENT_UNECESSARY_CROSS_CONTEXT =
<add> "org.apache.pluto.PREVENT_UNECESSARY_CROSS_CONTEXT";
<add>
<ide>
<ide> public static List<String> getSupportedContainerRuntimeOptions() {
<ide> String options = BUNDLE.getString(CONTAINER_RUNTIME_OPTIONS);
<ide> }
<ide> return result;
<ide> }
<add>
<add> private static Boolean prevent;
<add>
<add> public static boolean preventUnecessaryCrossContext() {
<add> if (prevent == null) {
<add> try {
<add> String test = BUNDLE.getString(PREVENT_UNECESSARY_CROSS_CONTEXT);
<add> prevent = new Boolean(test);
<add> } catch (MissingResourceException mre) {
<add> prevent = Boolean.FALSE;
<add> }
<add> }
<add> return prevent.booleanValue();
<add> }
<ide> } |
|
Java | bsd-3-clause | 544ef25e9855396180ff220691bd2082df9fc8ce | 0 | tomgullo/rexster,tomgullo/rexster,tomgullo/rexster,tingletech/rexster-tomcat,tomgullo/rexster,alszeb/rexster,alszeb/rexster,alszeb/rexster,alszeb/rexster,tingletech/rexster-tomcat,tingletech/rexster-tomcat | package com.tinkerpop.rexster.extension;
import com.tinkerpop.rexster.Tokens;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONObject;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Wraps the Jersey response object with some simple response builder methods.
*/
public class ExtensionResponse {
private Response jerseyResponse;
private boolean errorResponse;
/**
* Create a non-error ExtensionResponse object.
*/
public ExtensionResponse(Response response) {
this(response, false);
}
/**
* Create an ExtensionResponse object.
*/
public ExtensionResponse(Response response, boolean errorResponse) {
this.jerseyResponse = response;
this.errorResponse = errorResponse;
}
/**
* Override the builder and literally construct the Jersey response.
* <p/>
* Rexster will add its standard headers and override any provided in the response. It is recommended
* to use the @see error methods as opposed to override if the intention is to return an error on
* the response. The override methods will not throw a WebApplicationException or do any standard
* Rexster server side logging.
*/
public static ExtensionResponse override(Response response) {
if (response == null) {
throw new IllegalArgumentException("Response cannot be null");
}
return new ExtensionResponse(response);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(String message) {
return error(message, (Exception) null);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(String message, String appendKey, JSONObject appendJson) {
return error(message, null, appendKey, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*
* @param appendJson Additional JSON to push into the response. The root of the key values from this object
* will be merged into the root of the resulting JSON.
*/
public static ExtensionResponse error(String message, JSONObject appendJson) {
return error(message, null, null, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(Exception source) {
return error("", source);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(Exception source, String appendKey, JSONObject appendJson) {
return error("", source, appendKey, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*
* @param appendJson Additional JSON to push into the response. The root of the key values from this object
* will be merged into the root of the resulting JSON.
*/
public static ExtensionResponse error(Exception source, JSONObject appendJson) {
return error("", source, null, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(String message, Exception source) {
return error(message, source, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*
* @param appendKey This parameter is only relevant if the appendJson parameter is passed. If this value
* is not null or non-empty the value of appendJson will be assigned to this key value in
* the response object. If the key is null or empty the appendJson parameter will be
* written at the root of the response object.
* @param appendJson Additional JSON to push into the response.
*/
public static ExtensionResponse error(String message, Exception source, String appendKey, JSONObject appendJson) {
return error(message, source, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), appendKey, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*
* @param appendJson Additional JSON to push into the response. The root of the key values from this object
* will be merged into the root of the resulting JSON.
*/
public static ExtensionResponse error(String message, Exception source, JSONObject appendJson) {
return error(message, source, null, appendJson);
}
/**
* Generates standard Rexster JSON error with a specified server error response code.
* <p/>
* The status code is not validated, so throw the right code.
*/
public static ExtensionResponse error(String message, Exception source, int statusCode) {
return error(message, source, statusCode, null, null);
}
/**
* Generates standard Rexster JSON error with a specified server error response code.
* <p/>
* The status code is not validated, so throw the right code.
*
* @param appendKey This parameter is only relevant if the appendJson parameter is passed. If this value
* is not null or non-empty the value of appendJson will be assigned to this key value in
* the response object. If the key is null or empty the appendJson parameter will be
* written at the root of the response object.
* @param appendJson Additional JSON to push into the response.
*/
public static ExtensionResponse error(String message, Exception source, int statusCode, String appendKey, JSONObject appendJson) {
Map<String, Object> m = new HashMap<String, Object>();
m.put(Tokens.MESSAGE, message);
if (source != null) {
m.put("error", source.getMessage());
}
if (appendJson != null) {
if (appendKey != null && !appendKey.isEmpty()) {
m.put(appendKey, appendJson);
} else {
Iterator keys = appendJson.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
m.put(key, appendJson.opt(key));
}
}
}
// use a hashmap with the constructor so that a JSONException
// will not be thrown
return new ExtensionResponse(Response.status(statusCode).entity(new JSONObject(m)).build(), true);
}
/**
* Generates a response with no content and matching status code.
*/
public static ExtensionResponse noContent() {
return new ExtensionResponse(Response.noContent().build());
}
/**
* Generates an response with an OK status code. Accepts a HashMap as the response value.
* It is converted to JSON.
*/
public static ExtensionResponse ok(Map result) {
if (result == null) {
throw new IllegalArgumentException("result cannot be null");
}
return ok(new JSONObject(result));
}
public static ExtensionResponse availableOptions(String ... methods) {
return new ExtensionResponse(Response.noContent()
.header("Access-Control-Allow-Methods", StringUtils.join(methods, ",")).build());
}
/**
* Generates an response with an OK status code.
*/
public static ExtensionResponse ok(JSONObject result) {
return new ExtensionResponse(Response.ok(result).build());
}
public Response getJerseyResponse() {
return this.jerseyResponse;
}
public boolean isErrorResponse() {
return this.errorResponse;
}
}
| src/main/java/com/tinkerpop/rexster/extension/ExtensionResponse.java | package com.tinkerpop.rexster.extension;
import com.tinkerpop.rexster.Tokens;
import org.codehaus.jettison.json.JSONObject;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Wraps the Jersey response object with some simple response builder methods.
*/
public class ExtensionResponse {
private Response jerseyResponse;
private boolean errorResponse;
/**
* Create a non-error ExtensionResponse object.
*/
public ExtensionResponse(Response response) {
this(response, false);
}
/**
* Create an ExtensionResponse object.
*/
public ExtensionResponse(Response response, boolean errorResponse) {
this.jerseyResponse = response;
this.errorResponse = errorResponse;
}
/**
* Override the builder and literally construct the Jersey response.
* <p/>
* Rexster will add its standard headers and override any provided in the response. It is recommended
* to use the @see error methods as opposed to override if the intention is to return an error on
* the response. The override methods will not throw a WebApplicationException or do any standard
* Rexster server side logging.
*/
public static ExtensionResponse override(Response response) {
if (response == null) {
throw new IllegalArgumentException("Response cannot be null");
}
return new ExtensionResponse(response);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(String message) {
return error(message, (Exception) null);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(String message, String appendKey, JSONObject appendJson) {
return error(message, null, appendKey, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*
* @param appendJson Additional JSON to push into the response. The root of the key values from this object
* will be merged into the root of the resulting JSON.
*/
public static ExtensionResponse error(String message, JSONObject appendJson) {
return error(message, null, null, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(Exception source) {
return error("", source);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(Exception source, String appendKey, JSONObject appendJson) {
return error("", source, appendKey, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*
* @param appendJson Additional JSON to push into the response. The root of the key values from this object
* will be merged into the root of the resulting JSON.
*/
public static ExtensionResponse error(Exception source, JSONObject appendJson) {
return error("", source, null, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*/
public static ExtensionResponse error(String message, Exception source) {
return error(message, source, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*
* @param appendKey This parameter is only relevant if the appendJson parameter is passed. If this value
* is not null or non-empty the value of appendJson will be assigned to this key value in
* the response object. If the key is null or empty the appendJson parameter will be
* written at the root of the response object.
* @param appendJson Additional JSON to push into the response.
*/
public static ExtensionResponse error(String message, Exception source, String appendKey, JSONObject appendJson) {
return error(message, source, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), appendKey, appendJson);
}
/**
* Generates standard Rexster JSON error with an internal server error response code.
*
* @param appendJson Additional JSON to push into the response. The root of the key values from this object
* will be merged into the root of the resulting JSON.
*/
public static ExtensionResponse error(String message, Exception source, JSONObject appendJson) {
return error(message, source, null, appendJson);
}
/**
* Generates standard Rexster JSON error with a specified server error response code.
* <p/>
* The status code is not validated, so throw the right code.
*/
public static ExtensionResponse error(String message, Exception source, int statusCode) {
return error(message, source, statusCode, null, null);
}
/**
* Generates standard Rexster JSON error with a specified server error response code.
* <p/>
* The status code is not validated, so throw the right code.
*
* @param appendKey This parameter is only relevant if the appendJson parameter is passed. If this value
* is not null or non-empty the value of appendJson will be assigned to this key value in
* the response object. If the key is null or empty the appendJson parameter will be
* written at the root of the response object.
* @param appendJson Additional JSON to push into the response.
*/
public static ExtensionResponse error(String message, Exception source, int statusCode, String appendKey, JSONObject appendJson) {
Map<String, Object> m = new HashMap<String, Object>();
m.put(Tokens.MESSAGE, message);
if (source != null) {
m.put("error", source.getMessage());
}
if (appendJson != null) {
if (appendKey != null && !appendKey.isEmpty()) {
m.put(appendKey, appendJson);
} else {
Iterator keys = appendJson.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
m.put(key, appendJson.opt(key));
}
}
}
// use a hashmap with the constructor so that a JSONException
// will not be thrown
return new ExtensionResponse(Response.status(statusCode).entity(new JSONObject(m)).build(), true);
}
/**
* Generates a response with no content and matching status code.
*/
public static ExtensionResponse noContent() {
return new ExtensionResponse(Response.noContent().build());
}
/**
* Generates an response with an OK status code. Accepts a HashMap as the response value.
* It is converted to JSON.
*/
public static ExtensionResponse ok(Map result) {
if (result == null) {
throw new IllegalArgumentException("result cannot be null");
}
return ok(new JSONObject(result));
}
/**
* Generates an response with an OK status code.
*/
public static ExtensionResponse ok(JSONObject result) {
return new ExtensionResponse(Response.ok(result).build());
}
public Response getJerseyResponse() {
return this.jerseyResponse;
}
public boolean isErrorResponse() {
return this.errorResponse;
}
}
| Added helper method to build an OPTIONS response for extensions.
| src/main/java/com/tinkerpop/rexster/extension/ExtensionResponse.java | Added helper method to build an OPTIONS response for extensions. | <ide><path>rc/main/java/com/tinkerpop/rexster/extension/ExtensionResponse.java
<ide> package com.tinkerpop.rexster.extension;
<ide>
<ide> import com.tinkerpop.rexster.Tokens;
<add>import org.apache.commons.lang.StringUtils;
<ide> import org.codehaus.jettison.json.JSONObject;
<ide>
<ide> import javax.ws.rs.core.Response;
<ide> return ok(new JSONObject(result));
<ide> }
<ide>
<add> public static ExtensionResponse availableOptions(String ... methods) {
<add> return new ExtensionResponse(Response.noContent()
<add> .header("Access-Control-Allow-Methods", StringUtils.join(methods, ",")).build());
<add> }
<add>
<ide> /**
<ide> * Generates an response with an OK status code.
<ide> */ |
|
Java | apache-2.0 | 0251f0af9be3010f7762401bf41b640e254141d1 | 0 | googleinterns/gpay-virtual-queue,googleinterns/gpay-virtual-queue,googleinterns/gpay-virtual-queue | /*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.gpay.virtualqueue.backendservice.repository;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.gpay.virtualqueue.backendservice.model.Shop;
import com.google.gpay.virtualqueue.backendservice.model.Token;
import com.google.gpay.virtualqueue.backendservice.model.Shop.ShopStatus;
import com.google.gpay.virtualqueue.backendservice.model.Token.Status;
import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest;
import com.google.gpay.virtualqueue.backendservice.proto.UpdateShopStatusRequest;
import com.google.gpay.virtualqueue.backendservice.proto.UpdateShopStatusResponse;
import com.google.gpay.virtualqueue.backendservice.proto.UpdateTokenStatusRequest;
import com.google.gpay.virtualqueue.backendservice.proto.UpdateTokenStatusResponse;
import static com.google.gpay.virtualqueue.backendservice.repository.InMemoryVirtualQueueRepository.WAITING_TIME_MINS;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = InMemoryVirtualQueueRepository.class)
public class InMemoryVirtualQueueRepositoryTest {
InMemoryVirtualQueueRepository inMemoryVirtualQueueRepository = new InMemoryVirtualQueueRepository();
private static final String SHOP_OWNER_ID = "uid";
private static final String SHOP_NAME = "shopName";
private static final String SHOP_ADDRESS = "address";
private static final String PHONE_NUMBER = "+919012192800";
private static final String SHOP_TYPE = "shopType";
@BeforeEach
public void setUp() {
inMemoryVirtualQueueRepository.getTokenMap().clear();
inMemoryVirtualQueueRepository.getShopMap().clear();
inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().clear();
inMemoryVirtualQueueRepository.getShopIdToLastAllotedTokenMap().clear();
inMemoryVirtualQueueRepository.getShopOwnerMap().clear();
}
@Test
public void testCreateShop_success() throws Exception {
// Arrange.
CreateShopRequest shop = new CreateShopRequest(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
// Act.
UUID shopId = inMemoryVirtualQueueRepository.createShop(shop);
// Assert.
assertEquals("Size of shopMap", 1, inMemoryVirtualQueueRepository.getShopMap().size());
assertEquals("Shop Owner Id ", SHOP_OWNER_ID,
inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopOwnerId());
assertEquals("Shop Name ", SHOP_NAME, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopName());
assertEquals("Shop Address ", SHOP_ADDRESS,
inMemoryVirtualQueueRepository.getShopMap().get(shopId).getAddress());
assertEquals("Shop Phone Number ", PHONE_NUMBER,
inMemoryVirtualQueueRepository.getShopMap().get(shopId).getPhoneNumber());
assertEquals("Shop Type ", SHOP_TYPE, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopType());
}
@Test
public void testGetWaitingTime() throws Exception {
long waitingTime = inMemoryVirtualQueueRepository.getWaitingTime();
assertEquals("Waiting Time per customer is", WAITING_TIME_MINS, waitingTime);
}
@Test
public void testGetNewToken_success() throws Exception {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
addTokenListToShop(shopId);
// Act.
Token newToken = inMemoryVirtualQueueRepository.getNewToken(shopId);
// Assert.
UUID tokenId = newToken.getTokenId();
int expectedTokenMapSize = 1;
Integer expectedTokenNumber = 1;
UUID expectedShopId = inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getShopId();
assertEquals("Size of tokenMap", expectedTokenMapSize, inMemoryVirtualQueueRepository.getTokenMap().size());
assertEquals("Token number is", expectedTokenNumber, inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getTokenNumber());
assertEquals("Shop id is", expectedShopId, shopId);
}
@Test
public void testGetTokensForShop_success() throws Exception {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
addTokenListToShop(shopId);
// Act.
List<Token> getTokensResponseList = inMemoryVirtualQueueRepository.getTokens(shopId);
// Assert.
assertEquals("Size of token list", inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().get(shopId).stream().filter(token -> token.getStatus() == Status.ACTIVE).count(), getTokensResponseList.size());
}
@Test
public void testUpdateToken_success() throws Exception {
// Arrange.
UUID tokenId = addOneToken();
UpdateTokenStatusRequest updateTokenStatusRequest = new UpdateTokenStatusRequest(tokenId, Status.CANCELLED_BY_CUSTOMER);
// Act.
UpdateTokenStatusResponse updateTokenStatusResponse = inMemoryVirtualQueueRepository.updateToken(updateTokenStatusRequest);
// Assert.
assertEquals("token map status is", inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getStatus(), updateTokenStatusResponse.getUpdatedToken().getStatus());
}
@Test
public void testUpdateShop_success() throws Exception {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
addTokenListToShop(shopId);
UpdateShopStatusRequest updateShopStatusRequest = new UpdateShopStatusRequest(shopId, ShopStatus.DELETED);
// Act.
UpdateShopStatusResponse updateShopStatusResponse = inMemoryVirtualQueueRepository.updateShop(updateShopStatusRequest);
// Assert.
assertEquals("Shop status is", ShopStatus.DELETED, updateShopStatusResponse.getShop().getStatus());
}
@Test
public void testGetCustomersAhead_success() throws Exception {
// Arrange.
UUID tokenId = addOneToken();
UUID shopId = inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getShopId();
addTokenListToShop(shopId);
// Act.
long customersAhead = inMemoryVirtualQueueRepository.getCustomersAhead(tokenId);
// Assert.
assertEquals("Number of customers ahead is", 1, customersAhead);
}
@Test
public void testGetShop_success() {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
// Act.
Shop newShop = inMemoryVirtualQueueRepository.getShop(shopId);
// Assert.
assertEquals("Shop Owner Id ", SHOP_OWNER_ID, newShop.getShopOwnerId());
assertEquals("Shop Name ", SHOP_NAME, newShop.getShopName());
assertEquals("Shop Address ", SHOP_ADDRESS, newShop.getAddress());
assertEquals("Shop Phone Number ", PHONE_NUMBER, newShop.getPhoneNumber());
assertEquals("Shop Type ", SHOP_TYPE, newShop.getShopType());
}
@Test
public void testCustomersInQueue_success() {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
addTokenListToShop(shopId);
// Act.
long customersInQueue = inMemoryVirtualQueueRepository.getCustomersInQueue(shopId);
// Assert.
assertEquals("Customers in Queue is ", 1, customersInQueue);
}
private UUID addOneToken() {
UUID tokenId = UUID.randomUUID();
UUID shopId = UUID.randomUUID();
Token token = new Token(tokenId, shopId, 1);
token.setStatus(Status.ACTIVE);
inMemoryVirtualQueueRepository.getTokenMap().put(tokenId, token);
return tokenId;
}
private UUID addShopToRepository(String shopOwnerId, String shopName, String shopAddress, String phoneNumber, String ShopType) {
Shop shop = new Shop(shopOwnerId, shopName, shopAddress, phoneNumber, ShopType);
shop.setStatus(ShopStatus.ACTIVE);
UUID shopId = UUID.randomUUID();
inMemoryVirtualQueueRepository.getShopMap().put(shopId, shop);
inMemoryVirtualQueueRepository.getShopIdToLastAllotedTokenMap().put(shopId, new AtomicInteger(0));
return shopId;
}
private void addTokenListToShop(UUID shopId) {
List<Token> tokens = new ArrayList<>();
tokens.add(new Token(UUID.randomUUID(), shopId, 1, Status.ACTIVE));
tokens.add(new Token(UUID.randomUUID(), shopId, 1, Status.EXPIRED));
tokens.add(new Token(UUID.randomUUID(), shopId, 1, Status.CANCELLED_BY_CUSTOMER));
inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().put(shopId, tokens);
}
}
| backendservice/src/test/java/com/google/gpay/virtualqueue/backendservice/repository/InMemoryVirtualQueueRepositoryTest.java | /*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.gpay.virtualqueue.backendservice.repository;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import com.google.gpay.virtualqueue.backendservice.model.Shop;
import com.google.gpay.virtualqueue.backendservice.model.Token;
import com.google.gpay.virtualqueue.backendservice.model.Shop.ShopStatus;
import com.google.gpay.virtualqueue.backendservice.model.Token.Status;
import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest;
import com.google.gpay.virtualqueue.backendservice.proto.UpdateShopStatusRequest;
import com.google.gpay.virtualqueue.backendservice.proto.UpdateShopStatusResponse;
import com.google.gpay.virtualqueue.backendservice.proto.UpdateTokenStatusRequest;
import com.google.gpay.virtualqueue.backendservice.proto.UpdateTokenStatusResponse;
import static com.google.gpay.virtualqueue.backendservice.repository.InMemoryVirtualQueueRepository.WAITING_TIME_MINS;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = InMemoryVirtualQueueRepository.class)
public class InMemoryVirtualQueueRepositoryTest {
InMemoryVirtualQueueRepository inMemoryVirtualQueueRepository = new InMemoryVirtualQueueRepository();
private static final String SHOP_OWNER_ID = "uid";
private static final String SHOP_NAME = "shopName";
private static final String SHOP_ADDRESS = "address";
private static final String PHONE_NUMBER = "+919012192800";
private static final String SHOP_TYPE = "shopType";
@BeforeEach
public void setUp() {
inMemoryVirtualQueueRepository.getTokenMap().clear();
inMemoryVirtualQueueRepository.getShopMap().clear();
inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().clear();
inMemoryVirtualQueueRepository.getShopIdToLastAllotedTokenMap().clear();
inMemoryVirtualQueueRepository.getShopOwnerMap().clear();
}
@Test
public void testCreateShop_success() throws Exception {
// Arrange.
CreateShopRequest shop = new CreateShopRequest(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
// Act.
UUID shopId = inMemoryVirtualQueueRepository.createShop(shop);
// Assert.
assertEquals("Size of shopMap", 1, inMemoryVirtualQueueRepository.getShopMap().size());
assertEquals("Shop Owner Id ", SHOP_OWNER_ID,
inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopOwnerId());
assertEquals("Shop Name ", SHOP_NAME, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopName());
assertEquals("Shop Address ", SHOP_ADDRESS,
inMemoryVirtualQueueRepository.getShopMap().get(shopId).getAddress());
assertEquals("Shop Phone Number ", PHONE_NUMBER,
inMemoryVirtualQueueRepository.getShopMap().get(shopId).getPhoneNumber());
assertEquals("Shop Type ", SHOP_TYPE, inMemoryVirtualQueueRepository.getShopMap().get(shopId).getShopType());
}
@Test
public void testGetWaitingTime() throws Exception {
long waitingTime = inMemoryVirtualQueueRepository.getWaitingTime();
assertEquals("Waiting Time per customer is", WAITING_TIME_MINS, waitingTime);
}
@Test
public void testGetNewToken_success() throws Exception {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
addTokenListToShop(shopId);
// Act.
Token newToken = inMemoryVirtualQueueRepository.getNewToken(shopId);
// Assert.
UUID tokenId = newToken.getTokenId();
int expectedTokenMapSize = 1;
Integer expectedTokenNumber = 1;
UUID expectedShopId = inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getShopId();
assertEquals("Size of tokenMap", expectedTokenMapSize, inMemoryVirtualQueueRepository.getTokenMap().size());
assertEquals("Token number is", expectedTokenNumber, inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getTokenNumber());
assertEquals("Shop id is", expectedShopId, shopId);
}
@Test
public void testGetTokensForShop_success() throws Exception {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
addTokenListToShop(shopId);
// Act.
List<Token> getTokensResponseList = inMemoryVirtualQueueRepository.getTokens(shopId);
// Assert.
assertEquals("Size of token list", inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().get(shopId).stream().filter(token -> token.getStatus() == Status.ACTIVE).count(), getTokensResponseList.size());
}
@Test
public void testUpdateToken_success() throws Exception {
// Arrange.
UUID tokenId = addOneToken();
UpdateTokenStatusRequest updateTokenStatusRequest = new UpdateTokenStatusRequest(tokenId, Status.CANCELLED_BY_CUSTOMER);
// Act.
UpdateTokenStatusResponse updateTokenStatusResponse = inMemoryVirtualQueueRepository.updateToken(updateTokenStatusRequest);
// Assert.
assertEquals("token map status is", inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getStatus(), updateTokenStatusResponse.getUpdatedToken().getStatus());
}
@Test
public void testUpdateShop_success() throws Exception {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
addTokenListToShop(shopId);
UpdateShopStatusRequest updateShopStatusRequest = new UpdateShopStatusRequest(shopId, ShopStatus.DELETED);
// Act.
UpdateShopStatusResponse updateShopStatusResponse = inMemoryVirtualQueueRepository.updateShop(updateShopStatusRequest);
// Assert.
assertEquals("Shop status is", ShopStatus.DELETED, updateShopStatusResponse.getShop().getStatus());
}
@Test
public void testGetCustomersAhead_success() throws Exception {
// Arrange.
UUID tokenId = addOneToken();
UUID shopId = inMemoryVirtualQueueRepository.getTokenMap().get(tokenId).getShopId();
addTokenListToShop(shopId);
// Act.
long customersAhead = inMemoryVirtualQueueRepository.getCustomersAhead(tokenId);
// Assert.
assertEquals("Number of customers ahead is", 1, customersAhead);
}
@Test
public void testGetShop_success() {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
// Act.
Shop newShop = inMemoryVirtualQueueRepository.getShop(shopId);
// Assert.
assertEquals("Shop Owner Id ", SHOP_OWNER_ID, newShop.getShopOwnerId());
assertEquals("Shop Name ", SHOP_NAME, newShop.getShopName());
assertEquals("Shop Address ", SHOP_ADDRESS, newShop.getAddress());
assertEquals("Shop Phone Number ", PHONE_NUMBER, newShop.getPhoneNumber());
assertEquals("Shop Type ", SHOP_TYPE, newShop.getShopType());
}
@Test
public void testCustomersInQueue_success() {
// Arrange.
UUID shopId = addShopToRepository(SHOP_OWNER_ID, SHOP_NAME, SHOP_ADDRESS, PHONE_NUMBER, SHOP_TYPE);
addTokenListToShop(shopId);
// Act.
long customersInQueue = inMemoryVirtualQueueRepository.getCustomersInQueue(shopId);
// Assert.
assertEquals("Customers in Queue is ", 1, customersInQueue);
}
private UUID addOneToken() {
UUID tokenId = UUID.randomUUID();
UUID shopId = UUID.randomUUID();
Token token = new Token(tokenId, shopId, 1);
token.setStatus(Status.ACTIVE);
inMemoryVirtualQueueRepository.getTokenMap().put(tokenId, token);
return tokenId;
}
private UUID addShopToRepository(String shopOwnerId, String shopName, String shopAddress, String phoneNumber, String ShopType) {
Shop shop = new Shop(shopOwnerId, shopName, shopAddress, phoneNumber, ShopType);
shop.setStatus(ShopStatus.ACTIVE);
UUID shopId = UUID.randomUUID();
inMemoryVirtualQueueRepository.getShopMap().put(shopId, shop);
inMemoryVirtualQueueRepository.getShopIdToLastAllotedTokenMap().put(shopId, new AtomicInteger(0));
return shopId;
}
private void addTokenListToShop(UUID shopId) {
List<Token> tokens = new ArrayList<>();
tokens.add(new Token(UUID.randomUUID(), shopId, 1, Status.ACTIVE));
tokens.add(new Token(UUID.randomUUID(), shopId, 1, Status.EXPIRED));
tokens.add(new Token(UUID.randomUUID(), shopId, 1, Status.CANCELLED_BY_CUSTOMER));
inMemoryVirtualQueueRepository.getShopIdToListOfTokensMap().put(shopId, tokens);
}
}
| remove unused import
| backendservice/src/test/java/com/google/gpay/virtualqueue/backendservice/repository/InMemoryVirtualQueueRepositoryTest.java | remove unused import | <ide><path>ackendservice/src/test/java/com/google/gpay/virtualqueue/backendservice/repository/InMemoryVirtualQueueRepositoryTest.java
<ide> import java.util.List;
<ide> import java.util.UUID;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<del>import java.util.stream.Collectors;
<ide>
<ide> import com.google.gpay.virtualqueue.backendservice.model.Shop;
<ide> import com.google.gpay.virtualqueue.backendservice.model.Token; |
|
Java | agpl-3.0 | c60caff5f2e4516049e71665eb3fd6e6e3753757 | 0 | tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,aihua/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github | //
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2002-2003 The OpenNMS Group, Inc. All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// Copyright (C) 1999-2001 Oculan Corp. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information contact:
// OpenNMS Licensing <[email protected]>
// http://www.opennms.org/
// http://www.opennms.com/
//
// Tab Size = 8
//
package org.opennms.protocols.snmp;
import java.io.Serializable;
import org.opennms.protocols.snmp.asn1.AsnDecodingException;
import org.opennms.protocols.snmp.asn1.AsnEncoder;
import org.opennms.protocols.snmp.asn1.AsnEncodingException;
/**
* Implements the ASN1.UNIVERSAL Octet String datatype. The string is a sequence
* of 8-bit octet data. The format of the 8-bit characters are defined by the
* application.
*
* @version 1.1.1.1
* @author <a href="mailto:[email protected]>Brian Weaver </a>
*/
public class SnmpOctetString extends Object implements SnmpSyntax, Cloneable, Serializable {
/**
* Required to allow evolution of serialization format.
*/
static final long serialVersionUID = 1848780739976444105L; // generated by
// serialver
// tool
/**
* The actual octet string data (UTF-8)
*
*/
private byte[] m_data;
/**
* The ASN.1 value for the OCTET STRING type.
*
*/
public static final byte ASNTYPE = SnmpSMI.SMI_STRING;
/**
* This can be used by a derived class to <em>force</em> the data
* contained by the octet string. The data is not duplicated, only the
* reference to the array is stored. No validation of data is performed at
* all.
*
* @param data
* The new data buffer.
*/
protected void assumeString(byte[] data) {
m_data = data;
}
/**
* The default class constructor. Constructs an Octet String with a length
* of zero and no data.
*
*/
public SnmpOctetString() {
m_data = null;
}
/**
* Constructs an octet string with the inital value equal to data. The data
* is actually copied so changes to the data reference do not affect the
* Octet string object.
*
* @param data
* The data to be copied to self
*
*/
public SnmpOctetString(byte[] data) {
this();
if (data != null) {
m_data = new byte[data.length];
System.arraycopy(data, 0, m_data, 0, data.length);
}
}
/**
* Class copy constructor. Constructs and octet string object that is a
* duplicate of the object second.
*
* @param second
* The object to copy into self
*
*/
public SnmpOctetString(SnmpOctetString second) {
this(second.m_data);
}
/**
* Returns a reference to the internal object string. Changes to this byte
* array WILL affect the octet string object. These changes should not be
* made lightly.
*
* @return A reference to the internal byte array.
*/
public byte[] getString() {
return m_data;
}
/**
* Sets the internal string array so that it is identical to the passed
* array. The array is actually copied so that changes to data after the
* construction of the object are not reflected in the SnmpOctetString
* Object.
*
* @param data
* The new octet string data.
*
*/
public void setString(byte[] data) {
m_data = null;
if (data != null) {
m_data = new byte[data.length];
System.arraycopy(data, 0, m_data, 0, data.length);
}
}
/**
* Sets the internal octet string equal to the converted stirng via the
* method getBytes(). This may cause some data corruption since the
* conversion is platform specific.
*
* @param data
* The new octet string data.
*
* @see java.lang.String#getBytes()
*/
public void setString(String data) {
m_data = null;
if (data != null) {
m_data = data.getBytes();
}
}
/**
* Returns the internal length of the octet string. This method is favored
* over recovereing the length from the internal array. The method
* compensates for a null set of data and returns zero if the internal array
* is null.
*
* @return The length of the octet string.
*
*/
public int getLength() {
int len = 0;
if (m_data != null)
len = m_data.length;
return len;
}
/**
* Returns the ASN.1 type identifier for the Octet String.
*
* @return The ASN.1 identifier.
*
*/
public byte typeId() {
return ASNTYPE;
}
/**
* Encodes the ASN.1 octet string using the passed encoder and stores the
* results in the passed buffer. An exception is thrown if an error occurs
* with the encoding of the information.
*
* @param buf
* The buffer to write the encoded information.
* @param offset
* The offset to start writing information
* @param encoder
* The encoder object.
*
* @return The offset of the byte immediantly after the last encoded byte.
*
* @exception AsnEncodingException
* Thrown if the encoder finds an error in the buffer.
*/
public int encodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnEncodingException {
if (m_data == null)
throw new AsnEncodingException("No data in octet string");
return encoder.buildString(buf, offset, typeId(), m_data);
}
/**
* Decodes the ASN.1 octet string from the passed buffer. If an error occurs
* during the decoding sequence then an AsnDecodingException is thrown by
* the method. The value is decoded using the AsnEncoder passed to the
* object.
*
* @param buf
* The encode buffer
* @param offset
* The offset byte to begin decoding
* @param encoder
* The decoder object.
*
* @return The index of the byte immediantly after the last decoded byte of
* information.
*
* @exception AsnDecodingException
* Thrown by the encoder if an error occurs trying to decode
* the data buffer.
*/
public int decodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnDecodingException {
Object[] rVals = encoder.parseString(buf, offset);
if (((Byte) rVals[1]).byteValue() != typeId())
throw new AsnDecodingException("Invalid ASN.1 type");
m_data = (byte[]) rVals[2];
return ((Integer) rVals[0]).intValue();
}
/**
* Creates a duplicate copy of the object and returns it to the caller.
*
* @return A newly constructed copy of self
*
*/
public SnmpSyntax duplicate() {
return new SnmpOctetString(this);
}
/**
* Creates a duplicate copy of the object and returns it to the caller.
*
* @return A newly constructed copy of self
*
*/
public Object clone() {
return new SnmpOctetString(this);
}
/**
* Returns a string representation of the object. If the object contains
* non-printable characters then the contents are printed in hexidecimal.
*
*/
public String toString() {
//
// check for non-printable characters. If they
// exist then print the string out as hexidecimal
//
boolean asHex = false;
for (int i = 0; i < m_data.length; i++) {
byte b = m_data[i];
if ((b < 32 && b != 10 && b != 13) || b == 127) {
asHex = true;
break;
}
}
String rs = null;
if (asHex) {
//
// format the string for hex
//
StringBuffer b = new StringBuffer();
// b.append("SNMP Octet String [length = " + m_data.length + ", fmt
// = HEX] = [");
for (int i = 0; i < m_data.length; ++i) {
int x = (int) m_data[i] & 0xff;
if (x < 16)
b.append('0');
b.append(Integer.toString(x, 16).toUpperCase());
if (i < m_data.length - 1)
b.append(' ');
}
// b.append(']');
rs = b.toString();
} else {
//
// raw output
//
// rs = "SNMP Octet String [length = " + m_data.length + ", fmt =
// RAW] = [" + new String(m_data) + "]";
rs = new String(m_data);
}
return rs;
}
/**
* This method takes an SnmpOctetString and replaces any unprintable
* characters with ASCII period ('.') and returns the resulting character
* string. Special case in which the supplied SnmpOctetString consists of a
* single ASCII Null byte is also handled. In this special case an empty
* string is returned.
*
* NOTE: A character is considered unprintable if its decimal value falls
* outside of the range: 32 - 126.
*
* @param octetString
* SnmpOctetString from which to generate the String
*
* @return a Java String object created from the octet string's byte array.
*/
public static String toDisplayString(SnmpOctetString octetString) {
// TODO: Move this to a more common place
// Valid SnmpOctetString object
if (octetString == null) {
return null;
}
byte bytes[] = octetString.getString();
// Sanity check
if (bytes == null || bytes.length == 0) {
return null;
}
// Check for special case where byte array contains a single
// ASCII null character
if (bytes.length == 1 && bytes[0] == 0) {
return null;
}
// Replace all unprintable chars (chars outside of
// decimal range 32 - 126 inclusive) with an
// ASCII period char (decimal 46).
//
byte newBytes[] = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] < 32 || bytes[i] > 126) {
newBytes[i] = 46; // ASCII period '.'
}
}
// Create string, trim any white-space and return
String result = new String(newBytes);
return result.trim();
}
// TODO: Move this to common base class
public static String toHexString(SnmpOctetString ostr) {
if (ostr == null) return null;
StringBuffer sbuf = new StringBuffer();
if (ostr != null && ostr.getLength() > 0) {
byte[] bytes = ostr.getString();
for (int i = 0; i < bytes.length; i++) {
sbuf.append(Integer.toHexString(((int) bytes[i] >> 4) & 0xf));
sbuf.append(Integer.toHexString((int) bytes[i] & 0xf));
}
}
String physAddr = sbuf.toString().trim();
return physAddr;
}
public boolean equals(Object obj) {
if (obj instanceof SnmpOctetString) {
SnmpOctetString str = (SnmpOctetString)obj;
if (m_data == null) return (str.m_data == null);
if (m_data.length != str.m_data.length) return false;
for(int i = 0; i < m_data.length; i++)
if (m_data[i] != str.m_data[i])
return false;
return true;
}
return false;
}
public int hashCode() {
return 0;
}
}
| src/joesnmp/org/opennms/protocols/snmp/SnmpOctetString.java | //
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2002-2003 The OpenNMS Group, Inc. All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// Copyright (C) 1999-2001 Oculan Corp. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information contact:
// OpenNMS Licensing <[email protected]>
// http://www.opennms.org/
// http://www.opennms.com/
//
// Tab Size = 8
//
package org.opennms.protocols.snmp;
import java.io.Serializable;
import org.opennms.protocols.snmp.asn1.AsnDecodingException;
import org.opennms.protocols.snmp.asn1.AsnEncoder;
import org.opennms.protocols.snmp.asn1.AsnEncodingException;
/**
* Implements the ASN1.UNIVERSAL Octet String datatype. The string is a sequence
* of 8-bit octet data. The format of the 8-bit characters are defined by the
* application.
*
* @version 1.1.1.1
* @author <a href="mailto:[email protected]>Brian Weaver </a>
*/
public class SnmpOctetString extends Object implements SnmpSyntax, Cloneable, Serializable {
/**
* Required to allow evolution of serialization format.
*/
static final long serialVersionUID = 1848780739976444105L; // generated by
// serialver
// tool
/**
* The actual octet string data (UTF-8)
*
*/
private byte[] m_data;
/**
* The ASN.1 value for the OCTET STRING type.
*
*/
public static final byte ASNTYPE = SnmpSMI.SMI_STRING;
/**
* This can be used by a derived class to <em>force</em> the data
* contained by the octet string. The data is not duplicated, only the
* reference to the array is stored. No validation of data is performed at
* all.
*
* @param data
* The new data buffer.
*/
protected void assumeString(byte[] data) {
m_data = data;
}
/**
* The default class constructor. Constructs an Octet String with a length
* of zero and no data.
*
*/
public SnmpOctetString() {
m_data = null;
}
/**
* Constructs an octet string with the inital value equal to data. The data
* is actually copied so changes to the data reference do not affect the
* Octet string object.
*
* @param data
* The data to be copied to self
*
*/
public SnmpOctetString(byte[] data) {
this();
if (data != null) {
m_data = new byte[data.length];
System.arraycopy(data, 0, m_data, 0, data.length);
}
}
/**
* Class copy constructor. Constructs and octet string object that is a
* duplicate of the object second.
*
* @param second
* The object to copy into self
*
*/
public SnmpOctetString(SnmpOctetString second) {
this(second.m_data);
}
/**
* Returns a reference to the internal object string. Changes to this byte
* array WILL affect the octet string object. These changes should not be
* made lightly.
*
* @return A reference to the internal byte array.
*/
public byte[] getString() {
return m_data;
}
/**
* Sets the internal string array so that it is identical to the passed
* array. The array is actually copied so that changes to data after the
* construction of the object are not reflected in the SnmpOctetString
* Object.
*
* @param data
* The new octet string data.
*
*/
public void setString(byte[] data) {
m_data = null;
if (data != null) {
m_data = new byte[data.length];
System.arraycopy(data, 0, m_data, 0, data.length);
}
}
/**
* Sets the internal octet string equal to the converted stirng via the
* method getBytes(). This may cause some data corruption since the
* conversion is platform specific.
*
* @param data
* The new octet string data.
*
* @see java.lang.String#getBytes()
*/
public void setString(String data) {
m_data = null;
if (data != null) {
m_data = data.getBytes();
}
}
/**
* Returns the internal length of the octet string. This method is favored
* over recovereing the length from the internal array. The method
* compensates for a null set of data and returns zero if the internal array
* is null.
*
* @return The length of the octet string.
*
*/
public int getLength() {
int len = 0;
if (m_data != null)
len = m_data.length;
return len;
}
/**
* Returns the ASN.1 type identifier for the Octet String.
*
* @return The ASN.1 identifier.
*
*/
public byte typeId() {
return ASNTYPE;
}
/**
* Encodes the ASN.1 octet string using the passed encoder and stores the
* results in the passed buffer. An exception is thrown if an error occurs
* with the encoding of the information.
*
* @param buf
* The buffer to write the encoded information.
* @param offset
* The offset to start writing information
* @param encoder
* The encoder object.
*
* @return The offset of the byte immediantly after the last encoded byte.
*
* @exception AsnEncodingException
* Thrown if the encoder finds an error in the buffer.
*/
public int encodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnEncodingException {
if (m_data == null)
throw new AsnEncodingException("No data in octet string");
return encoder.buildString(buf, offset, typeId(), m_data);
}
/**
* Decodes the ASN.1 octet string from the passed buffer. If an error occurs
* during the decoding sequence then an AsnDecodingException is thrown by
* the method. The value is decoded using the AsnEncoder passed to the
* object.
*
* @param buf
* The encode buffer
* @param offset
* The offset byte to begin decoding
* @param encoder
* The decoder object.
*
* @return The index of the byte immediantly after the last decoded byte of
* information.
*
* @exception AsnDecodingException
* Thrown by the encoder if an error occurs trying to decode
* the data buffer.
*/
public int decodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnDecodingException {
Object[] rVals = encoder.parseString(buf, offset);
if (((Byte) rVals[1]).byteValue() != typeId())
throw new AsnDecodingException("Invalid ASN.1 type");
m_data = (byte[]) rVals[2];
return ((Integer) rVals[0]).intValue();
}
/**
* Creates a duplicate copy of the object and returns it to the caller.
*
* @return A newly constructed copy of self
*
*/
public SnmpSyntax duplicate() {
return new SnmpOctetString(this);
}
/**
* Creates a duplicate copy of the object and returns it to the caller.
*
* @return A newly constructed copy of self
*
*/
public Object clone() {
return new SnmpOctetString(this);
}
/**
* Returns a string representation of the object. If the object contains
* non-printable characters then the contents are printed in hexidecimal.
*
*/
public String toString() {
//
// check for non-printable characters. If they
// exist then print the string out as hexidecimal
//
boolean asHex = false;
for (int i = 0; i < m_data.length; i++) {
byte b = m_data[i];
if ((b < 32 && b != 10 && b != 13) || b == 127) {
asHex = true;
break;
}
}
String rs = null;
if (asHex) {
//
// format the string for hex
//
StringBuffer b = new StringBuffer();
// b.append("SNMP Octet String [length = " + m_data.length + ", fmt
// = HEX] = [");
for (int i = 0; i < m_data.length; ++i) {
int x = (int) m_data[i] & 0xff;
if (x < 16)
b.append('0');
b.append(Integer.toString(x, 16).toUpperCase());
if (i < m_data.length - 1)
b.append(' ');
}
// b.append(']');
rs = b.toString();
} else {
//
// raw output
//
// rs = "SNMP Octet String [length = " + m_data.length + ", fmt =
// RAW] = [" + new String(m_data) + "]";
rs = new String(m_data);
}
return rs;
}
/**
* This method takes an SnmpOctetString and replaces any unprintable
* characters with ASCII period ('.') and returns the resulting character
* string. Special case in which the supplied SnmpOctetString consists of a
* single ASCII Null byte is also handled. In this special case an empty
* string is returned.
*
* NOTE: A character is considered unprintable if its decimal value falls
* outside of the range: 32 - 126.
*
* @param octetString
* SnmpOctetString from which to generate the String
*
* @return a Java String object created from the octet string's byte array.
*/
public static String toDisplayString(SnmpOctetString octetString) {
// TODO: Move this to a more common place
// Valid SnmpOctetString object
if (octetString == null) {
return null;
}
byte bytes[] = octetString.getString();
// Sanity check
if (bytes == null || bytes.length == 0) {
return null;
}
// Check for special case where byte array contains a single
// ASCII null character
if (bytes.length == 1 && bytes[0] == 0) {
return null;
}
// Replace all unprintable chars (chars outside of
// decimal range 32 - 126 inclusive) with an
// ASCII period char (decimal 46).
//
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] < 32 || bytes[i] > 126) {
bytes[i] = 46; // ASCII period '.'
}
}
// Create string, trim any white-space and return
String result = new String(bytes);
return result.trim();
}
// TODO: Move this to common base class
public static String toHexString(SnmpOctetString ostr) {
if (ostr == null) return null;
StringBuffer sbuf = new StringBuffer();
if (ostr != null && ostr.getLength() > 0) {
byte[] bytes = ostr.getString();
for (int i = 0; i < bytes.length; i++) {
sbuf.append(Integer.toHexString(((int) bytes[i] >> 4) & 0xf));
sbuf.append(Integer.toHexString((int) bytes[i] & 0xf));
}
}
String physAddr = sbuf.toString().trim();
return physAddr;
}
public boolean equals(Object obj) {
if (obj instanceof SnmpOctetString) {
SnmpOctetString str = (SnmpOctetString)obj;
if (m_data == null) return (str.m_data == null);
if (m_data.length != str.m_data.length) return false;
for(int i = 0; i < m_data.length; i++)
if (m_data[i] != str.m_data[i])
return false;
return true;
}
return false;
}
public int hashCode() {
return 0;
}
}
| don't modify the SnmpOctetSTring while converting to a DisplayString
| src/joesnmp/org/opennms/protocols/snmp/SnmpOctetString.java | don't modify the SnmpOctetSTring while converting to a DisplayString | <ide><path>rc/joesnmp/org/opennms/protocols/snmp/SnmpOctetString.java
<ide> // decimal range 32 - 126 inclusive) with an
<ide> // ASCII period char (decimal 46).
<ide> //
<add> byte newBytes[] = new byte[bytes.length];
<ide> for (int i = 0; i < bytes.length; i++) {
<ide> if (bytes[i] < 32 || bytes[i] > 126) {
<del> bytes[i] = 46; // ASCII period '.'
<add> newBytes[i] = 46; // ASCII period '.'
<ide> }
<ide> }
<ide>
<ide> // Create string, trim any white-space and return
<del> String result = new String(bytes);
<add> String result = new String(newBytes);
<ide> return result.trim();
<ide> }
<ide> |
|
JavaScript | bsd-2-clause | 9424a36f2e76a414f92cefd42d492b75942cd464 | 0 | jlord/balrog,jlord/balrog,IonicaBizauKitchen/balrog,IonicaBizauKitchen/balrog | var marked = require('marked')
module.exports = function parser(contents) {
var result = extractMetaMatter(contents)
var content = removeHeaders(contents)
result.content = marked(content.toString('utf-8'))
return result
}
function getMetaLines(contents) {
var lines = contents.toString('utf-8').split('\n')
var end = 4
for (var i = 0; i < 4; i++) {
if (!lines[i]) {
end = i
}
}
return lines.slice(0, end)
}
function extractMetaMatter(contents) {
var meta = getMetaLines(contents)
.filter(onlyHeaders)
.map(stripHeaders)
return {
title: meta[0],
author: meta[1],
date: meta[2],
tags: meta[3] && meta[3].split(/,\s*/),
}
}
function onlyHeaders(string) {
return /\s*#+\s/.test(string)
}
function stripHeaders(string) {
return string.replace(/\s*#+\s/, '');
}
function removeHeaders(contents) {
var lines = contents.toString('utf-8').split('\n')
// the headers are the first lines of the
// document with # until the first ''
// so see where that '' occurs to know
// when to cut for the body
var cut = 4
for (var i = 0; i < 4; i++) {
if (!lines[i]) {
cut = i
}
}
var headers = lines.filter(onlyHeaders)
return lines.splice(cut, lines.length).join('\n')
} | lib/parse-markdown.js | var marked = require('marked')
module.exports = function parser(contents) {
var result = extractMetaMatter(contents)
var content = removeHeaders(contents)
result.content = marked(content.toString('utf-8'))
return result
}
function getMetaLines(contents) {
var lines = contents.toString('utf-8').split('\n')
return lines.slice(0, 4)
}
function extractMetaMatter(contents) {
var meta = getMetaLines(contents)
.filter(onlyHeaders)
.map(stripHeaders)
return {
title: meta[0],
author: meta[1],
date: meta[2],
tags: meta[3] && meta[3].split(/,\s*/),
}
}
function onlyHeaders(string) {
return /\s*#+\s/.test(string)
}
function stripHeaders(string) {
return string.replace(/\s*#+\s/, '');
}
function removeHeaders(contents) {
var lines = contents.toString('utf-8').split('\n')
var headers = lines.filter(onlyHeaders)
return lines.splice(headers.length, lines.length).join('\n')
}
| Better Header Logic
See when the first line break is to determine how many headers a page
has and therefore know where to cut for the body and metadata
| lib/parse-markdown.js | Better Header Logic | <ide><path>ib/parse-markdown.js
<ide>
<ide> function getMetaLines(contents) {
<ide> var lines = contents.toString('utf-8').split('\n')
<del> return lines.slice(0, 4)
<add> var end = 4
<add>
<add> for (var i = 0; i < 4; i++) {
<add> if (!lines[i]) {
<add> end = i
<add> }
<add> }
<add>
<add> return lines.slice(0, end)
<ide> }
<ide>
<ide> function extractMetaMatter(contents) {
<ide>
<ide> function removeHeaders(contents) {
<ide> var lines = contents.toString('utf-8').split('\n')
<add>
<add> // the headers are the first lines of the
<add> // document with # until the first ''
<add> // so see where that '' occurs to know
<add> // when to cut for the body
<add>
<add> var cut = 4
<add> for (var i = 0; i < 4; i++) {
<add> if (!lines[i]) {
<add> cut = i
<add> }
<add> }
<add>
<ide> var headers = lines.filter(onlyHeaders)
<del> return lines.splice(headers.length, lines.length).join('\n')
<add> return lines.splice(cut, lines.length).join('\n')
<ide> }
<del> |
|
Java | apache-2.0 | f33ad067449df0c2d641e89e12d5ca571bc80639 | 0 | graben/aries,alien11689/aries,apache/aries,apache/aries,alien11689/aries,graben/aries,rotty3000/aries,rotty3000/aries,apache/aries,graben/aries,graben/aries,alien11689/aries,apache/aries,alien11689/aries,rotty3000/aries,rotty3000/aries | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.container;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.Validator;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.reflect.BeanArgumentImpl;
import org.apache.aries.blueprint.reflect.BeanMetadataImpl;
import org.apache.aries.blueprint.reflect.BeanPropertyImpl;
import org.apache.aries.blueprint.reflect.CollectionMetadataImpl;
import org.apache.aries.blueprint.reflect.IdRefMetadataImpl;
import org.apache.aries.blueprint.reflect.MapEntryImpl;
import org.apache.aries.blueprint.reflect.MapMetadataImpl;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.apache.aries.blueprint.reflect.PropsMetadataImpl;
import org.apache.aries.blueprint.reflect.RefMetadataImpl;
import org.apache.aries.blueprint.reflect.ReferenceListMetadataImpl;
import org.apache.aries.blueprint.reflect.ReferenceListenerImpl;
import org.apache.aries.blueprint.reflect.ReferenceMetadataImpl;
import org.apache.aries.blueprint.reflect.RegistrationListenerImpl;
import org.apache.aries.blueprint.reflect.ServiceMetadataImpl;
import org.apache.aries.blueprint.reflect.ServiceReferenceMetadataImpl;
import org.apache.aries.blueprint.reflect.ValueMetadataImpl;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.NullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.osgi.service.blueprint.reflect.ValueMetadata;
import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
public class Parser {
public static final String BLUEPRINT_NAMESPACE = "http://www.osgi.org/xmlns/blueprint/v1.0.0";
public static final String BLUEPRINT_ELEMENT = "blueprint";
public static final String DESCRIPTION_ELEMENT = "description";
public static final String TYPE_CONVERTERS_ELEMENT = "type-converters";
public static final String BEAN_ELEMENT = "bean";
public static final String ARGUMENT_ELEMENT = "argument";
public static final String REF_ELEMENT = "ref";
public static final String IDREF_ELEMENT = "idref";
public static final String LIST_ELEMENT = "list";
public static final String SET_ELEMENT = "set";
public static final String MAP_ELEMENT = "map";
public static final String ARRAY_ELEMENT = "array";
public static final String PROPS_ELEMENT = "props";
public static final String PROP_ELEMENT = "prop";
public static final String PROPERTY_ELEMENT = "property";
public static final String NULL_ELEMENT = "null";
public static final String VALUE_ELEMENT = "value";
public static final String SERVICE_ELEMENT = "service";
public static final String REFERENCE_ELEMENT = "reference";
public static final String REFERENCE_LIST_ELEMENT = "reference-list";
public static final String INTERFACES_ELEMENT = "interfaces";
public static final String REFERENCE_LISTENER_ELEMENT = "reference-listener";
public static final String SERVICE_PROPERTIES_ELEMENT = "service-properties";
public static final String REGISTRATION_LISTENER_ELEMENT = "registration-listener";
public static final String ENTRY_ELEMENT = "entry";
public static final String KEY_ELEMENT = "key";
public static final String DEFAULT_ACTIVATION_ATTRIBUTE = "default-activation";
public static final String DEFAULT_TIMEOUT_ATTRIBUTE = "default-timeout";
public static final String DEFAULT_AVAILABILITY_ATTRIBUTE = "default-availability";
public static final String NAME_ATTRIBUTE = "name";
public static final String ID_ATTRIBUTE = "id";
public static final String CLASS_ATTRIBUTE = "class";
public static final String INDEX_ATTRIBUTE = "index";
public static final String TYPE_ATTRIBUTE = "type";
public static final String VALUE_ATTRIBUTE = "value";
public static final String VALUE_REF_ATTRIBUTE = "value-ref";
public static final String KEY_ATTRIBUTE = "key";
public static final String KEY_REF_ATTRIBUTE = "key-ref";
public static final String REF_ATTRIBUTE = "ref";
public static final String COMPONENT_ID_ATTRIBUTE = "component-id";
public static final String INTERFACE_ATTRIBUTE = "interface";
public static final String DEPENDS_ON_ATTRIBUTE = "depends-on";
public static final String AUTO_EXPORT_ATTRIBUTE = "auto-export";
public static final String RANKING_ATTRIBUTE = "ranking";
public static final String TIMEOUT_ATTRIBUTE = "timeout";
public static final String FILTER_ATTRIBUTE = "filter";
public static final String COMPONENT_NAME_ATTRIBUTE = "component-name";
public static final String AVAILABILITY_ATTRIBUTE = "availability";
public static final String REGISTRATION_METHOD_ATTRIBUTE = "registration-method";
public static final String UNREGISTRATION_METHOD_ATTRIBUTE = "unregistration-method";
public static final String BIND_METHOD_ATTRIBUTE = "bind-method";
public static final String UNBIND_METHOD_ATTRIBUTE = "unbind-method";
public static final String KEY_TYPE_ATTRIBUTE = "key-type";
public static final String VALUE_TYPE_ATTRIBUTE = "value-type";
public static final String MEMBER_TYPE_ATTRIBUTE = "member-type";
public static final String SCOPE_ATTRIBUTE = "scope";
public static final String INIT_METHOD_ATTRIBUTE = "init-method";
public static final String DESTROY_METHOD_ATTRIBUTE = "destroy-method";
public static final String ACTIVATION_ATTRIBUTE = "activation";
public static final String FACTORY_REF_ATTRIBUTE = "factory-ref";
public static final String FACTORY_METHOD_ATTRIBUTE = "factory-method";
public static final String AUTO_EXPORT_DISABLED = "disabled";
public static final String AUTO_EXPORT_INTERFACES = "interfaces";
public static final String AUTO_EXPORT_CLASS_HIERARCHY = "class-hierarchy";
public static final String AUTO_EXPORT_ALL = "all-classes";
public static final String AUTO_EXPORT_DEFAULT = AUTO_EXPORT_DISABLED;
public static final String RANKING_DEFAULT = "0";
public static final String AVAILABILITY_MANDATORY = "mandatory";
public static final String AVAILABILITY_OPTIONAL = "optional";
public static final String AVAILABILITY_DEFAULT = AVAILABILITY_MANDATORY;
public static final String TIMEOUT_DEFAULT = "300000";
public static final String USE_SERVICE_OBJECT = "service-object";
public static final String USE_SERVICE_REFERENCE = "service-reference";
public static final String ACTIVATION_EAGER = "eager";
public static final String ACTIVATION_LAZY = "lazy";
public static final String ACTIVATION_DEFAULT = ACTIVATION_EAGER;
private static DocumentBuilderFactory documentBuilderFactory;
private final List<Document> documents = new ArrayList<Document>();
private ComponentDefinitionRegistry registry;
private NamespaceHandlerRegistry.NamespaceHandlerSet handlers;
private String idPrefix = "component-";
private Set<String> ids = new HashSet<String>();
private int idCounter;
private String defaultTimeout;
private String defaultAvailability;
private String defaultActivation;
private Set<URI> namespaces;
public Parser() {
}
public Parser(String idPrefix) {
this.idPrefix = idPrefix;
}
/**
* Parse an input stream for blueprint xml.
* @param inputStream The data to parse. The caller is responsible for closing the stream afterwards.
* @throws Exception on parse error
*/
public void parse(InputStream inputStream) throws Exception {
InputSource inputSource = new InputSource(inputStream);
DocumentBuilder builder = getDocumentBuilderFactory().newDocumentBuilder();
Document doc = builder.parse(inputSource);
documents.add(doc);
}
/**
* Parse blueprint xml referred to by a list of URLs
* @param urls URLs to blueprint xml to parse
* @throws Exception on parse error
*/
public void parse(List<URL> urls) throws Exception {
// Create document builder factory
// Load documents
for (URL url : urls) {
InputStream inputStream = url.openStream();
try {
parse (inputStream);
} finally {
inputStream.close();
}
}
}
public Set<URI> getNamespaces() {
if (this.namespaces == null) {
Set<URI> namespaces = new LinkedHashSet<URI>();
for (Document doc : documents) {
findNamespaces(namespaces, doc);
}
this.namespaces = namespaces;
}
return this.namespaces;
}
private void findNamespaces(Set<URI> namespaces, Node node) {
if (node instanceof Element || node instanceof Attr) {
String ns = node.getNamespaceURI();
if (ns != null && !isBlueprintNamespace(ns) && !isIgnorableAttributeNamespace(ns)) {
namespaces.add(URI.create(ns));
}else if ( ns == null && //attributes from blueprint are unqualified as per schema.
node instanceof Attr &&
SCOPE_ATTRIBUTE.equals(node.getNodeName()) &&
((Attr)node).getOwnerElement() != null && //should never occur from parsed doc.
BLUEPRINT_NAMESPACE.equals(((Attr)node).getOwnerElement().getNamespaceURI()) &&
BEAN_ELEMENT.equals(((Attr)node).getOwnerElement().getLocalName()) ){
//Scope attribute is special case, as may contain namespace usage within its value.
URI scopeNS = getNamespaceForAttributeValue(node);
if(scopeNS!=null){
namespaces.add(scopeNS);
}
}
}
NamedNodeMap nnm = node.getAttributes();
if(nnm!=null){
for(int i = 0; i< nnm.getLength() ; i++){
findNamespaces(namespaces, nnm.item(i));
}
}
NodeList nl = node.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
findNamespaces(namespaces, nl.item(i));
}
}
public void populate(NamespaceHandlerRegistry.NamespaceHandlerSet handlers,
ComponentDefinitionRegistry registry) {
this.handlers = handlers;
this.registry = registry;
if (this.documents == null) {
throw new IllegalStateException("Documents should be parsed before populating the registry");
}
// Parse components
for (Document doc : this.documents) {
loadComponents(doc);
}
}
public void validate(Schema schema) {
try {
Validator validator = schema.newValidator();
for (Document doc : this.documents) {
validator.validate(new DOMSource(doc));
}
} catch (Exception e) {
throw new ComponentDefinitionException("Unable to validate xml", e);
}
}
private void loadComponents(Document doc) {
defaultTimeout = TIMEOUT_DEFAULT;
defaultAvailability = AVAILABILITY_DEFAULT;
defaultActivation = ACTIVATION_DEFAULT;
Element root = doc.getDocumentElement();
if (!isBlueprintNamespace(root.getNamespaceURI()) ||
!nodeNameEquals(root, BLUEPRINT_ELEMENT)) {
throw new ComponentDefinitionException("Root element must be {" + BLUEPRINT_NAMESPACE + "}" + BLUEPRINT_ELEMENT + " element");
}
// Parse global attributes
if (root.hasAttribute(DEFAULT_ACTIVATION_ATTRIBUTE)) {
defaultActivation = root.getAttribute(DEFAULT_ACTIVATION_ATTRIBUTE);
}
if (root.hasAttribute(DEFAULT_TIMEOUT_ATTRIBUTE)) {
defaultTimeout = root.getAttribute(DEFAULT_TIMEOUT_ATTRIBUTE);
}
if (root.hasAttribute(DEFAULT_AVAILABILITY_ATTRIBUTE)) {
defaultAvailability = root.getAttribute(DEFAULT_AVAILABILITY_ATTRIBUTE);
}
// Parse custom attributes
NamedNodeMap attributes = root.getAttributes();
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
if (node instanceof Attr
&& node.getNamespaceURI() != null
&& !isBlueprintNamespace(node.getNamespaceURI())
&& !XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(node.getNamespaceURI())
&& XMLConstants.XMLNS_ATTRIBUTE.equals(node.getNodeName())) {
decorateCustomNode(node, null);
}
}
}
// Parse elements
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element element = (Element) node;
String namespaceUri = element.getNamespaceURI();
if (isBlueprintNamespace(namespaceUri)) {
parseBlueprintElement(element);
} else {
Metadata component = parseCustomElement(element, null);
if (component != null) {
if (!(component instanceof ComponentMetadata)) {
throw new ComponentDefinitionException("Expected a ComponentMetadata to be returned when parsing element " + element.getNodeName());
}
registry.registerComponentDefinition((ComponentMetadata) component);
}
}
}
}
}
public <T> T parseElement(Class<T> type, ComponentMetadata enclosingComponent, Element element) {
if (BeanArgument.class.isAssignableFrom(type)) {
return type.cast(parseBeanArgument(enclosingComponent, element));
} else if (BeanProperty.class.isAssignableFrom(type)) {
return type.cast(parseBeanProperty(enclosingComponent, element));
} else if (MapEntry.class.isAssignableFrom(type)) {
return type.cast(parseMapEntry(element, enclosingComponent, null, null));
} else if (MapMetadata.class.isAssignableFrom(type)) {
return type.cast(parseMap(element, enclosingComponent));
} else if (BeanMetadata.class.isAssignableFrom(type)) {
return type.cast(parseBeanMetadata(element, false));
} else if (NullMetadata.class.isAssignableFrom(type)) {
return type.cast(NullMetadata.NULL);
} else if (CollectionMetadata.class.isAssignableFrom(type)) {
return type.cast(parseCollection(Collection.class, element, enclosingComponent));
} else if (PropsMetadata.class.isAssignableFrom(type)) {
return type.cast(parseProps(element));
} else if (ReferenceMetadata.class.isAssignableFrom(type)) {
return type.cast(parseReference(element, enclosingComponent == null));
} else if (ReferenceListMetadata.class.isAssignableFrom(type)) {
return type.cast(parseRefList(element, enclosingComponent == null));
} else if (IdRefMetadata.class.isAssignableFrom(type)) {
return type.cast(parseIdRef(element));
} else if (RefMetadata.class.isAssignableFrom(type)) {
return type.cast(parseRef(element));
} else if (ValueMetadata.class.isAssignableFrom(type)) {
return type.cast(parseValue(element, null));
} else if (ReferenceListener.class.isAssignableFrom(type)) {
return type.cast(parseServiceListener(element, enclosingComponent));
} else {
throw new ComponentDefinitionException("Unknown type to parse element: " + type.getName());
}
}
private void parseBlueprintElement(Element element) {
if (nodeNameEquals(element, DESCRIPTION_ELEMENT)) {
// Ignore description
} else if (nodeNameEquals(element, TYPE_CONVERTERS_ELEMENT)) {
parseTypeConverters(element);
} else if (nodeNameEquals(element, BEAN_ELEMENT)) {
ComponentMetadata component = parseBeanMetadata(element, true);
registry.registerComponentDefinition(component);
} else if (nodeNameEquals(element, SERVICE_ELEMENT)) {
ComponentMetadata service = parseService(element, true);
registry.registerComponentDefinition(service);
} else if (nodeNameEquals(element, REFERENCE_ELEMENT)) {
ComponentMetadata reference = parseReference(element, true);
registry.registerComponentDefinition(reference);
} else if (nodeNameEquals(element, REFERENCE_LIST_ELEMENT) ) {
ComponentMetadata references = parseRefList(element, true);
registry.registerComponentDefinition(references);
} else {
throw new ComponentDefinitionException("Unknown element " + element.getNodeName() + " in namespace " + BLUEPRINT_NAMESPACE);
}
}
private void parseTypeConverters(Element element) {
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
Object target = null;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, BEAN_ELEMENT)) {
target = parseBeanMetadata(e, true);
} else if (nodeNameEquals(e, REF_ELEMENT)) {
String componentName = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
target = new RefMetadataImpl(componentName);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
target = parseReference(e, true);
}
} else {
target = parseCustomElement(e, null);
}
if (!(target instanceof Target)) {
throw new ComponentDefinitionException("Metadata parsed for element " + e.getNodeName() + " can not be used as a type converter");
}
registry.registerTypeConverter((Target) target);
}
}
}
/**
* Takes an Attribute Node containing a namespace prefix qualified attribute value, and resolves the namespace using the DOM Node.<br>
*
* @param attrNode The DOM Node with the qualified attribute value.
* @return The URI if one is resolvable, or null if the attr is null, or not namespace prefixed. (or not a DOM Attribute Node)
* @throws ComponentDefinitionException if the namespace prefix in the attribute value cannot be resolved.
*/
private URI getNamespaceForAttributeValue(Node attrNode) throws ComponentDefinitionException {
URI uri = null;
if(attrNode!=null && (attrNode instanceof Attr)){
Attr attr = (Attr)attrNode;
String attrValue = attr.getValue();
if(attrValue!=null && attrValue.indexOf(":")!=-1){
String parts[] = attrValue.split(":");
String uriStr = attr.getOwnerElement().lookupNamespaceURI(parts[0]);
if(uriStr!=null){
uri = URI.create(uriStr);
}else{
throw new ComponentDefinitionException("Unsupported attribute namespace prefix "+parts[0]+" "+attr);
}
}
}
return uri;
}
/**
* Tests if a scope attribute value is a custom scope, and if so invokes
* the appropriate namespace handler, passing the blueprint scope node.
* <p>
* Currently this tests for custom scope by looking for the presence of
* a ':' char within the scope attribute value. This is valid as long as
* the blueprint schema continues to restrict that custom scopes should
* require that characters presence.
* <p>
*
* @param scope Value of scope attribute
* @param bean DOM element for bean associated to this scope
* @return Metadata as processed by NS Handler.
* @throws ComponentDefinitionException if an undeclared prefix is used,
* if a namespace handler is unavailable for a resolved prefix,
* or if the resolved prefix results as the blueprint namespace.
*/
private ComponentMetadata handleCustomScope(Node scope, Element bean, ComponentMetadata metadata){
URI scopeNS = getNamespaceForAttributeValue(scope);
if(scopeNS!=null && !BLUEPRINT_NAMESPACE.equals(scopeNS.toString())){
NamespaceHandler nsHandler = getNamespaceHandler(scopeNS);
ParserContextImpl context = new ParserContextImpl(this, registry, metadata, scope);
metadata = nsHandler.decorate(scope, metadata, context);
}else if(scopeNS!=null){
throw new ComponentDefinitionException("Custom scopes cannot use the blueprint namespace "+scope);
}
return metadata;
}
private ComponentMetadata parseBeanMetadata(Element element, boolean topElement) {
BeanMetadataImpl metadata = new BeanMetadataImpl();
if (topElement) {
metadata.setId(getId(element));
if (element.hasAttribute(SCOPE_ATTRIBUTE)) {
metadata.setScope(element.getAttribute(SCOPE_ATTRIBUTE));
if (metadata.getScope().equals(BeanMetadata.SCOPE_PROTOTYPE)) {
if (element.hasAttribute(ACTIVATION_ATTRIBUTE)) {
if (element.getAttribute(ACTIVATION_ATTRIBUTE).equals(ACTIVATION_EAGER)) {
throw new ComponentDefinitionException("A <bean> with a prototype scope can not have an eager activation");
}
}
metadata.setActivation(ComponentMetadata.ACTIVATION_LAZY);
} else {
metadata.setActivation(parseActivation(element));
}
} else {
metadata.setActivation(parseActivation(element));
}
} else {
metadata.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(CLASS_ATTRIBUTE)) {
metadata.setClassName(element.getAttribute(CLASS_ATTRIBUTE));
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
metadata.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
if (element.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
metadata.setInitMethod(element.getAttribute(INIT_METHOD_ATTRIBUTE));
}
if (element.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
metadata.setDestroyMethod(element.getAttribute(DESTROY_METHOD_ATTRIBUTE));
}
if (element.hasAttribute(FACTORY_REF_ATTRIBUTE)) {
metadata.setFactoryComponent(new RefMetadataImpl(element.getAttribute(FACTORY_REF_ATTRIBUTE)));
}
if (element.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
String factoryMethod = element.getAttribute(FACTORY_METHOD_ATTRIBUTE);
metadata.setFactoryMethod(factoryMethod);
}
// Do some validation
if (metadata.getClassName() == null && metadata.getFactoryComponent() == null) {
throw new ComponentDefinitionException("Bean class or factory-ref must be specified");
}
if (metadata.getFactoryComponent() != null && metadata.getFactoryMethod() == null) {
throw new ComponentDefinitionException("factory-method is required when factory-component is set");
}
if (MetadataUtil.isPrototypeScope(metadata) && metadata.getDestroyMethod() != null) {
throw new ComponentDefinitionException("destroy-method must not be set for a <bean> with a prototype scope");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(node.getNamespaceURI())) {
if (nodeNameEquals(node, ARGUMENT_ELEMENT)) {
metadata.addArgument(parseBeanArgument(metadata, e));
} else if (nodeNameEquals(node, PROPERTY_ELEMENT)) {
metadata.addProperty(parseBeanProperty(metadata, e));
}
}
}
}
MetadataUtil.validateBeanArguments(metadata.getArguments());
ComponentMetadata m = metadata;
// Parse custom scopes
m = handleCustomScope(element.getAttributeNode(SCOPE_ATTRIBUTE), element, m);
// Parse custom attributes
m = handleCustomAttributes(element.getAttributes(), m);
// Parse custom elements;
m = handleCustomElements(element, m);
return m;
}
public BeanProperty parseBeanProperty(ComponentMetadata enclosingComponent, Element element) {
String name = element.hasAttribute(NAME_ATTRIBUTE) ? element.getAttribute(NAME_ATTRIBUTE) : null;
Metadata value = parseArgumentOrPropertyValue(element, enclosingComponent);
return new BeanPropertyImpl(name, value);
}
private BeanArgument parseBeanArgument(ComponentMetadata enclosingComponent, Element element) {
int index = element.hasAttribute(INDEX_ATTRIBUTE) ? Integer.parseInt(element.getAttribute(INDEX_ATTRIBUTE)) : -1;
String type = element.hasAttribute(TYPE_ATTRIBUTE) ? element.getAttribute(TYPE_ATTRIBUTE) : null;
Metadata value = parseArgumentOrPropertyValue(element, enclosingComponent);
return new BeanArgumentImpl(value, type, index);
}
private ComponentMetadata parseService(Element element, boolean topElement) {
ServiceMetadataImpl service = new ServiceMetadataImpl();
boolean hasInterfaceNameAttribute = false;
if (topElement) {
service.setId(getId(element));
service.setActivation(parseActivation(element));
} else {
service.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(INTERFACE_ATTRIBUTE)) {
service.setInterfaceNames(Collections.singletonList(element.getAttribute(INTERFACE_ATTRIBUTE)));
hasInterfaceNameAttribute = true;
}
if (element.hasAttribute(REF_ATTRIBUTE)) {
service.setServiceComponent(new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE)));
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
service.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
String autoExport = element.hasAttribute(AUTO_EXPORT_ATTRIBUTE) ? element.getAttribute(AUTO_EXPORT_ATTRIBUTE) : AUTO_EXPORT_DEFAULT;
if (AUTO_EXPORT_DISABLED.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_DISABLED);
} else if (AUTO_EXPORT_INTERFACES.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_INTERFACES);
} else if (AUTO_EXPORT_CLASS_HIERARCHY.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY);
} else if (AUTO_EXPORT_ALL.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_ALL_CLASSES);
} else {
throw new ComponentDefinitionException("Illegal value (" + autoExport + ") for " + AUTO_EXPORT_ATTRIBUTE + " attribute");
}
String ranking = element.hasAttribute(RANKING_ATTRIBUTE) ? element.getAttribute(RANKING_ATTRIBUTE) : RANKING_DEFAULT;
try {
service.setRanking(Integer.parseInt(ranking));
} catch (NumberFormatException e) {
throw new ComponentDefinitionException("Attribute " + RANKING_ATTRIBUTE + " must be a valid integer (was: " + ranking + ")");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, INTERFACES_ELEMENT)) {
if (hasInterfaceNameAttribute) {
throw new ComponentDefinitionException("Only one of " + INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must be used");
}
service.setInterfaceNames(parseInterfaceNames(e));
} else if (nodeNameEquals(e, SERVICE_PROPERTIES_ELEMENT)) {
List<MapEntry> entries = parseServiceProperties(e, service).getEntries();
service.setServiceProperties(entries);
} else if (nodeNameEquals(e, REGISTRATION_LISTENER_ELEMENT)) {
service.addRegistrationListener(parseRegistrationListener(e, service));
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
service.setServiceComponent((Target) parseBeanMetadata(e, false));
} else if (nodeNameEquals(e, REF_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
service.setServiceComponent(new RefMetadataImpl(component));
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
service.setServiceComponent((Target) parseReference(e, false));
}
}
}
}
// Check service
if (service.getServiceComponent() == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element must be set");
}
// Check interface
if (service.getAutoExport() == ServiceMetadata.AUTO_EXPORT_DISABLED && service.getInterfaces().isEmpty()) {
throw new ComponentDefinitionException(INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must be set when " + AUTO_EXPORT_ATTRIBUTE + " is set to " + AUTO_EXPORT_DISABLED);
}
// Check for non-disabled auto-exports and interfaces
if (service.getAutoExport() != ServiceMetadata.AUTO_EXPORT_DISABLED && !service.getInterfaces().isEmpty()) {
throw new ComponentDefinitionException(INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must not be set when " + AUTO_EXPORT_ATTRIBUTE + " is set to anything else than " + AUTO_EXPORT_DISABLED);
}
ComponentMetadata s = service;
// Parse custom attributes
s = handleCustomAttributes(element.getAttributes(), s);
// Parse custom elements;
s = handleCustomElements(element, s);
return s;
}
private CollectionMetadata parseArray(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(Object[].class, element, enclosingComponent);
}
private CollectionMetadata parseList(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(List.class, element, enclosingComponent);
}
private CollectionMetadata parseSet(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(Set.class, element, enclosingComponent);
}
private CollectionMetadata parseCollection(Class collectionType, Element element, ComponentMetadata enclosingComponent) {
// Parse attributes
String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
// Parse elements
List<Metadata> list = new ArrayList<Metadata>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Metadata val = parseValueGroup((Element) node, enclosingComponent, null, true);
list.add(val);
}
}
return new CollectionMetadataImpl(collectionType, valueType, list);
}
public PropsMetadata parseProps(Element element) {
// Parse elements
List<MapEntry> entries = new ArrayList<MapEntry>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI()) && nodeNameEquals(e, PROP_ELEMENT)) {
entries.add(parseProperty(e));
}
}
}
return new PropsMetadataImpl(entries);
}
private MapEntry parseProperty(Element element) {
// Parse attributes
if (!element.hasAttribute(KEY_ATTRIBUTE)) {
throw new ComponentDefinitionException(KEY_ATTRIBUTE + " attribute is required");
}
String value;
if (element.hasAttribute(VALUE_ATTRIBUTE)) {
value = element.getAttribute(VALUE_ATTRIBUTE);
} else {
value = getTextValue(element);
}
String key = element.getAttribute(KEY_ATTRIBUTE);
return new MapEntryImpl(new ValueMetadataImpl(key), new ValueMetadataImpl(value));
}
public MapMetadata parseMap(Element element, ComponentMetadata enclosingComponent) {
// Parse attributes
String keyType = element.hasAttribute(KEY_TYPE_ATTRIBUTE) ? element.getAttribute(KEY_TYPE_ATTRIBUTE) : null;
String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
// Parse elements
List<MapEntry> entries = new ArrayList<MapEntry>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, ENTRY_ELEMENT)) {
entries.add(parseMapEntry(e, enclosingComponent, null, null));
}
}
}
return new MapMetadataImpl(keyType, valueType, entries);
}
private MapEntry parseMapEntry(Element element, ComponentMetadata enclosingComponent, String keyType, String valueType) {
// Parse attributes
String key = element.hasAttribute(KEY_ATTRIBUTE) ? element.getAttribute(KEY_ATTRIBUTE) : null;
String keyRef = element.hasAttribute(KEY_REF_ATTRIBUTE) ? element.getAttribute(KEY_REF_ATTRIBUTE) : null;
String value = element.hasAttribute(VALUE_ATTRIBUTE) ? element.getAttribute(VALUE_ATTRIBUTE) : null;
String valueRef = element.hasAttribute(VALUE_REF_ATTRIBUTE) ? element.getAttribute(VALUE_REF_ATTRIBUTE) : null;
// Parse elements
NonNullMetadata keyValue = null;
Metadata valValue = null;
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, KEY_ELEMENT)) {
keyValue = parseMapKeyEntry(e, enclosingComponent, keyType);
} else {
valValue = parseValueGroup(e, enclosingComponent, valueType, true);
}
}
}
// Check key
if (keyValue != null && (key != null || keyRef != null) || (keyValue == null && key == null && keyRef == null)) {
throw new ComponentDefinitionException("Only and only one of " + KEY_ATTRIBUTE + " attribute, " + KEY_REF_ATTRIBUTE + " attribute or " + KEY_ELEMENT + " element must be set");
} else if (keyValue == null && key != null) {
keyValue = new ValueMetadataImpl(key, keyType);
} else if (keyValue == null /*&& keyRef != null*/) {
keyValue = new RefMetadataImpl(keyRef);
}
// Check value
if (valValue != null && (value != null || valueRef != null) || (valValue == null && value == null && valueRef == null)) {
throw new ComponentDefinitionException("Only and only one of " + VALUE_ATTRIBUTE + " attribute, " + VALUE_REF_ATTRIBUTE + " attribute or sub element must be set");
} else if (valValue == null && value != null) {
valValue = new ValueMetadataImpl(value, valueType);
} else if (valValue == null /*&& valueRef != null*/) {
valValue = new RefMetadataImpl(valueRef);
}
return new MapEntryImpl(keyValue, valValue);
}
private NonNullMetadata parseMapKeyEntry(Element element, ComponentMetadata enclosingComponent, String keyType) {
NonNullMetadata keyValue = null;
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (keyValue != null) {
// TODO: throw an exception
}
keyValue = (NonNullMetadata) parseValueGroup(e, enclosingComponent, keyType, false);
break;
}
}
if (keyValue == null) {
// TODO: throw an exception
}
return keyValue;
}
public MapMetadata parseServiceProperties(Element element, ComponentMetadata enclosingComponent) {
// TODO: need to handle this better
MapMetadata map = parseMap(element, enclosingComponent);
handleCustomElements(element, enclosingComponent);
return map;
}
public RegistrationListener parseRegistrationListener(Element element, ComponentMetadata enclosingComponent) {
RegistrationListenerImpl listener = new RegistrationListenerImpl();
Metadata listenerComponent = null;
// Parse attributes
if (element.hasAttribute(REF_ATTRIBUTE)) {
listenerComponent = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
String registrationMethod = null;
if (element.hasAttribute(REGISTRATION_METHOD_ATTRIBUTE)) {
registrationMethod = element.getAttribute(REGISTRATION_METHOD_ATTRIBUTE);
listener.setRegistrationMethod(registrationMethod);
}
String unregistrationMethod = null;
if (element.hasAttribute(UNREGISTRATION_METHOD_ATTRIBUTE)) {
unregistrationMethod = element.getAttribute(UNREGISTRATION_METHOD_ATTRIBUTE);
listener.setUnregistrationMethod(unregistrationMethod);
}
if (registrationMethod == null && unregistrationMethod == null) {
throw new ComponentDefinitionException("One of " + REGISTRATION_METHOD_ATTRIBUTE + " or " + UNREGISTRATION_METHOD_ATTRIBUTE + " must be set");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REF_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
listenerComponent = new RefMetadataImpl(component);
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseBeanMetadata(e, false);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseReference(e, false);
} else if (nodeNameEquals(e, SERVICE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseService(e, false);
}
} else {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseCustomElement(e, enclosingComponent);
}
}
}
if (listenerComponent == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element must be set");
}
listener.setListenerComponent((Target) listenerComponent);
return listener;
}
private ComponentMetadata parseReference(Element element, boolean topElement) {
ReferenceMetadataImpl reference = new ReferenceMetadataImpl();
if (topElement) {
reference.setId(getId(element));
}
parseReference(element, reference, topElement);
String timeout = element.hasAttribute(TIMEOUT_ATTRIBUTE) ? element.getAttribute(TIMEOUT_ATTRIBUTE) : this.defaultTimeout;
try {
reference.setTimeout(Long.parseLong(timeout));
} catch (NumberFormatException e) {
throw new ComponentDefinitionException("Attribute " + TIMEOUT_ATTRIBUTE + " must be a valid long (was: " + timeout + ")");
}
ComponentMetadata r = reference;
// Parse custom attributes
r = handleCustomAttributes(element.getAttributes(), r);
// Parse custom elements;
r = handleCustomElements(element, r);
return r;
}
public String getDefaultTimeout() {
return defaultTimeout;
}
public String getDefaultAvailability() {
return defaultAvailability;
}
public String getDefaultActivation() {
return defaultActivation;
}
private ComponentMetadata parseRefList(Element element, boolean topElement) {
ReferenceListMetadataImpl references = new ReferenceListMetadataImpl();
if (topElement) {
references.setId(getId(element));
}
if (element.hasAttribute(MEMBER_TYPE_ATTRIBUTE)) {
String memberType = element.getAttribute(MEMBER_TYPE_ATTRIBUTE);
if (USE_SERVICE_OBJECT.equals(memberType)) {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_OBJECT);
} else if (USE_SERVICE_REFERENCE.equals(memberType)) {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_REFERENCE);
}
} else {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_OBJECT);
}
parseReference(element, references, topElement);
ComponentMetadata r = references;
// Parse custom attributes
r = handleCustomAttributes(element.getAttributes(), r);
// Parse custom elements;
r = handleCustomElements(element, r);
return r;
}
private void parseReference(Element element, ServiceReferenceMetadataImpl reference, boolean topElement) {
// Parse attributes
if (topElement) {
reference.setActivation(parseActivation(element));
} else {
reference.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
reference.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
if (element.hasAttribute(INTERFACE_ATTRIBUTE)) {
reference.setInterface(element.getAttribute(INTERFACE_ATTRIBUTE));
}
if (element.hasAttribute(FILTER_ATTRIBUTE)) {
reference.setFilter(element.getAttribute(FILTER_ATTRIBUTE));
}
if (element.hasAttribute(COMPONENT_NAME_ATTRIBUTE)) {
reference.setComponentName(element.getAttribute(COMPONENT_NAME_ATTRIBUTE));
}
String availability = element.hasAttribute(AVAILABILITY_ATTRIBUTE) ? element.getAttribute(AVAILABILITY_ATTRIBUTE) : defaultAvailability;
if (AVAILABILITY_MANDATORY.equals(availability)) {
reference.setAvailability(ServiceReferenceMetadata.AVAILABILITY_MANDATORY);
} else if (AVAILABILITY_OPTIONAL.equals(availability)) {
reference.setAvailability(ServiceReferenceMetadata.AVAILABILITY_OPTIONAL);
} else {
throw new ComponentDefinitionException("Illegal value for " + AVAILABILITY_ATTRIBUTE + " attribute: " + availability);
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REFERENCE_LISTENER_ELEMENT)) {
reference.addServiceListener(parseServiceListener(e, reference));
}
}
}
}
}
private ReferenceListener parseServiceListener(Element element, ComponentMetadata enclosingComponent) {
ReferenceListenerImpl listener = new ReferenceListenerImpl();
Metadata listenerComponent = null;
// Parse attributes
if (element.hasAttribute(REF_ATTRIBUTE)) {
listenerComponent = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
String bindMethodName = null;
String unbindMethodName = null;
if (element.hasAttribute(BIND_METHOD_ATTRIBUTE)) {
bindMethodName = element.getAttribute(BIND_METHOD_ATTRIBUTE);
listener.setBindMethod(bindMethodName);
}
if (element.hasAttribute(UNBIND_METHOD_ATTRIBUTE)) {
unbindMethodName = element.getAttribute(UNBIND_METHOD_ATTRIBUTE);
listener.setUnbindMethod(unbindMethodName);
}
if (bindMethodName == null && unbindMethodName == null) {
throw new ComponentDefinitionException("One of " + BIND_METHOD_ATTRIBUTE + " or " + UNBIND_METHOD_ATTRIBUTE + " must be set");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REF_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
listenerComponent = new RefMetadataImpl(component);
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseBeanMetadata(e, false);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseReference(e, false);
} else if (nodeNameEquals(e, SERVICE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseService(e, false);
}
} else {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseCustomElement(e, enclosingComponent);
}
}
}
if (listenerComponent == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element must be set");
}
listener.setListenerComponent((Target) listenerComponent);
return listener;
}
public List<String> parseInterfaceNames(Element element) {
List<String> interfaceNames = new ArrayList<String>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, VALUE_ELEMENT)) {
String v = getTextValue(e).trim();
if (interfaceNames.contains(v)) {
throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice");
}
interfaceNames.add(getTextValue(e));
} else {
throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element");
}
}
}
return interfaceNames;
}
private Metadata parseArgumentOrPropertyValue(Element element, ComponentMetadata enclosingComponent) {
Metadata [] values = new Metadata[3];
if (element.hasAttribute(REF_ATTRIBUTE)) {
values[0] = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
if (element.hasAttribute(VALUE_ATTRIBUTE)) {
values[1] = new ValueMetadataImpl(element.getAttribute(VALUE_ATTRIBUTE));
}
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(node.getNamespaceURI()) && nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
// Ignore description elements
} else {
values[2] = parseValueGroup(e, enclosingComponent, null, true);
break;
}
}
}
Metadata value = null;
for (Metadata v : values) {
if (v != null) {
if (value == null) {
value = v;
} else {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + VALUE_ATTRIBUTE + " attribute or sub element must be set");
}
}
}
if (value == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + VALUE_ATTRIBUTE + " attribute or sub element must be set");
}
return value;
}
private Metadata parseValueGroup(Element element, ComponentMetadata enclosingComponent, String collectionType, boolean allowNull) {
if (isBlueprintNamespace(element.getNamespaceURI())) {
if (nodeNameEquals(element, BEAN_ELEMENT)) {
return parseBeanMetadata(element, false);
} else if (nodeNameEquals(element, REFERENCE_ELEMENT)) {
return parseReference(element, false);
} else if (nodeNameEquals(element, SERVICE_ELEMENT)) {
return parseService(element, false);
} else if (nodeNameEquals(element, REFERENCE_LIST_ELEMENT) ) {
return parseRefList(element, false);
} else if (nodeNameEquals(element, NULL_ELEMENT) && allowNull) {
return NullMetadata.NULL;
} else if (nodeNameEquals(element, VALUE_ELEMENT)) {
return parseValue(element, collectionType);
} else if (nodeNameEquals(element, REF_ELEMENT)) {
return parseRef(element);
} else if (nodeNameEquals(element, IDREF_ELEMENT)) {
return parseIdRef(element);
} else if (nodeNameEquals(element, LIST_ELEMENT)) {
return parseList(element, enclosingComponent);
} else if (nodeNameEquals(element, SET_ELEMENT)) {
return parseSet(element, enclosingComponent);
} else if (nodeNameEquals(element, MAP_ELEMENT)) {
return parseMap(element, enclosingComponent);
} else if (nodeNameEquals(element, PROPS_ELEMENT)) {
return parseProps(element);
} else if (nodeNameEquals(element, ARRAY_ELEMENT)) {
return parseArray(element, enclosingComponent);
} else {
throw new ComponentDefinitionException("Unknown blueprint element " + element.getNodeName());
}
} else {
return parseCustomElement(element, enclosingComponent);
}
}
private ValueMetadata parseValue(Element element, String collectionType) {
String type;
if (element.hasAttribute(TYPE_ATTRIBUTE)) {
type = element.getAttribute(TYPE_ATTRIBUTE);
} else {
type = collectionType;
}
return new ValueMetadataImpl(getTextValue(element), type);
}
private RefMetadata parseRef(Element element) {
String component = element.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
return new RefMetadataImpl(component);
}
private Metadata parseIdRef(Element element) {
String component = element.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + IDREF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
return new IdRefMetadataImpl(component);
}
private int parseActivation(Element element) {
String initialization = element.hasAttribute(ACTIVATION_ATTRIBUTE) ? element.getAttribute(ACTIVATION_ATTRIBUTE) : defaultActivation;
if (ACTIVATION_EAGER.equals(initialization)) {
return ComponentMetadata.ACTIVATION_EAGER;
} else if (ACTIVATION_LAZY.equals(initialization)) {
return ComponentMetadata.ACTIVATION_LAZY;
} else {
throw new ComponentDefinitionException("Attribute " + ACTIVATION_ATTRIBUTE + " must be equal to " + ACTIVATION_EAGER + " or " + ACTIVATION_LAZY);
}
}
private ComponentMetadata handleCustomAttributes(NamedNodeMap attributes, ComponentMetadata enclosingComponent) {
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
//attr is custom if it has a namespace, and it isnt blueprint, or the xmlns ns.
//blueprint ns would be an error, as blueprint attrs are unqualified.
if (node instanceof Attr &&
node.getNamespaceURI() != null &&
!isBlueprintNamespace(node.getNamespaceURI()) &&
!isIgnorableAttributeNamespace(node.getNamespaceURI()) ) {
enclosingComponent = decorateCustomNode(node, enclosingComponent);
}
}
}
return enclosingComponent;
}
private ComponentMetadata handleCustomElements(Element element, ComponentMetadata enclosingComponent) {
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
if (!isBlueprintNamespace(node.getNamespaceURI())) {
enclosingComponent = decorateCustomNode(node, enclosingComponent);
}
}
}
return enclosingComponent;
}
private ComponentMetadata decorateCustomNode(Node node, ComponentMetadata enclosingComponent) {
NamespaceHandler handler = getNamespaceHandler(node);
ParserContextImpl context = new ParserContextImpl(this, registry, enclosingComponent, node);
return handler.decorate(node, enclosingComponent, context);
}
private Metadata parseCustomElement(Element element, ComponentMetadata enclosingComponent) {
NamespaceHandler handler = getNamespaceHandler(element);
ParserContextImpl context = new ParserContextImpl(this, registry, enclosingComponent, element);
return handler.parse(element, context);
}
private NamespaceHandler getNamespaceHandler(Node node) {
URI ns = URI.create(node.getNamespaceURI());
return getNamespaceHandler(ns);
}
private NamespaceHandler getNamespaceHandler(URI uri) {
if (handlers == null) {
throw new ComponentDefinitionException("Unsupported node (namespace handler registry is not set): " + uri);
}
NamespaceHandler handler = this.handlers.getNamespaceHandler(uri);
if (handler == null) {
throw new ComponentDefinitionException("Unsupported node namespace: " + uri);
}
return handler;
}
public String generateId() {
String id;
do {
id = "." + idPrefix + ++idCounter;
} while (ids.contains(id));
ids.add(id);
return id;
}
public String getId(Element element) {
String id;
if (element.hasAttribute(ID_ATTRIBUTE)) {
id = element.getAttribute(ID_ATTRIBUTE);
ids.add(id);
} else {
id = generateId();
}
return id;
}
public static boolean isBlueprintNamespace(String ns) {
return BLUEPRINT_NAMESPACE.equals(ns);
}
/**
* Test if this namespace uri does not require a Namespace Handler.<p>
* <li> XMLConstants.RELAXNG_NS_URI
* <li> XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI
* <li> XMLConstants.W3C_XML_SCHEMA_NS_URI
* <li> XMLConstants.W3C_XPATH_DATATYPE_NS_URI
* <li> XMLConstants.W3C_XPATH_DATATYPE_NS_URI
* <li> XMLConstants.XML_DTD_NS_URI
* <li> XMLConstants.XML_NS_URI
* <li> XMLConstants.XMLNS_ATTRIBUTE_NS_URI
* @param ns URI to be tested.
* @return true if the uri does not require a namespace handler.
*/
public static boolean isIgnorableAttributeNamespace(String ns) {
return XMLConstants.RELAXNG_NS_URI.equals(ns) ||
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI.equals(ns) ||
XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(ns) ||
XMLConstants.W3C_XPATH_DATATYPE_NS_URI.equals(ns) ||
XMLConstants.W3C_XPATH_DATATYPE_NS_URI.equals(ns) ||
XMLConstants.XML_DTD_NS_URI.equals(ns) ||
XMLConstants.XML_NS_URI.equals(ns) ||
XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(ns);
}
private static boolean nodeNameEquals(Node node, String name) {
return (name.equals(node.getNodeName()) || name.equals(node.getLocalName()));
}
private static List<String> parseList(String list) {
String[] items = list.split(" ");
List<String> set = new ArrayList<String>();
for (String item : items) {
item = item.trim();
if (item.length() > 0) {
set.add(item);
}
}
return set;
}
private static String getTextValue(Element element) {
StringBuffer value = new StringBuffer();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
value.append(item.getNodeValue());
}
}
return value.toString();
}
private static DocumentBuilderFactory getDocumentBuilderFactory() {
if (documentBuilderFactory == null) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
documentBuilderFactory = dbf;
}
return documentBuilderFactory;
}
}
| blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/Parser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.blueprint.container;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.Validator;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.reflect.BeanArgumentImpl;
import org.apache.aries.blueprint.reflect.BeanMetadataImpl;
import org.apache.aries.blueprint.reflect.BeanPropertyImpl;
import org.apache.aries.blueprint.reflect.CollectionMetadataImpl;
import org.apache.aries.blueprint.reflect.IdRefMetadataImpl;
import org.apache.aries.blueprint.reflect.MapEntryImpl;
import org.apache.aries.blueprint.reflect.MapMetadataImpl;
import org.apache.aries.blueprint.reflect.MetadataUtil;
import org.apache.aries.blueprint.reflect.PropsMetadataImpl;
import org.apache.aries.blueprint.reflect.RefMetadataImpl;
import org.apache.aries.blueprint.reflect.ReferenceListMetadataImpl;
import org.apache.aries.blueprint.reflect.ReferenceListenerImpl;
import org.apache.aries.blueprint.reflect.ReferenceMetadataImpl;
import org.apache.aries.blueprint.reflect.RegistrationListenerImpl;
import org.apache.aries.blueprint.reflect.ServiceMetadataImpl;
import org.apache.aries.blueprint.reflect.ServiceReferenceMetadataImpl;
import org.apache.aries.blueprint.reflect.ValueMetadataImpl;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NonNullMetadata;
import org.osgi.service.blueprint.reflect.NullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
import org.osgi.service.blueprint.reflect.Target;
import org.osgi.service.blueprint.reflect.ValueMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* TODO: javadoc
*
* @version $Rev$, $Date$
*/
public class Parser {
public static final String BLUEPRINT_NAMESPACE = "http://www.osgi.org/xmlns/blueprint/v1.0.0";
public static final String BLUEPRINT_ELEMENT = "blueprint";
public static final String DESCRIPTION_ELEMENT = "description";
public static final String TYPE_CONVERTERS_ELEMENT = "type-converters";
public static final String BEAN_ELEMENT = "bean";
public static final String ARGUMENT_ELEMENT = "argument";
public static final String REF_ELEMENT = "ref";
public static final String IDREF_ELEMENT = "idref";
public static final String LIST_ELEMENT = "list";
public static final String SET_ELEMENT = "set";
public static final String MAP_ELEMENT = "map";
public static final String ARRAY_ELEMENT = "array";
public static final String PROPS_ELEMENT = "props";
public static final String PROP_ELEMENT = "prop";
public static final String PROPERTY_ELEMENT = "property";
public static final String NULL_ELEMENT = "null";
public static final String VALUE_ELEMENT = "value";
public static final String SERVICE_ELEMENT = "service";
public static final String REFERENCE_ELEMENT = "reference";
public static final String REFERENCE_LIST_ELEMENT = "reference-list";
public static final String INTERFACES_ELEMENT = "interfaces";
public static final String REFERENCE_LISTENER_ELEMENT = "reference-listener";
public static final String SERVICE_PROPERTIES_ELEMENT = "service-properties";
public static final String REGISTRATION_LISTENER_ELEMENT = "registration-listener";
public static final String ENTRY_ELEMENT = "entry";
public static final String KEY_ELEMENT = "key";
public static final String DEFAULT_ACTIVATION_ATTRIBUTE = "default-activation";
public static final String DEFAULT_TIMEOUT_ATTRIBUTE = "default-timeout";
public static final String DEFAULT_AVAILABILITY_ATTRIBUTE = "default-availability";
public static final String NAME_ATTRIBUTE = "name";
public static final String ID_ATTRIBUTE = "id";
public static final String CLASS_ATTRIBUTE = "class";
public static final String INDEX_ATTRIBUTE = "index";
public static final String TYPE_ATTRIBUTE = "type";
public static final String VALUE_ATTRIBUTE = "value";
public static final String VALUE_REF_ATTRIBUTE = "value-ref";
public static final String KEY_ATTRIBUTE = "key";
public static final String KEY_REF_ATTRIBUTE = "key-ref";
public static final String REF_ATTRIBUTE = "ref";
public static final String COMPONENT_ID_ATTRIBUTE = "component-id";
public static final String INTERFACE_ATTRIBUTE = "interface";
public static final String DEPENDS_ON_ATTRIBUTE = "depends-on";
public static final String AUTO_EXPORT_ATTRIBUTE = "auto-export";
public static final String RANKING_ATTRIBUTE = "ranking";
public static final String TIMEOUT_ATTRIBUTE = "timeout";
public static final String FILTER_ATTRIBUTE = "filter";
public static final String COMPONENT_NAME_ATTRIBUTE = "component-name";
public static final String AVAILABILITY_ATTRIBUTE = "availability";
public static final String REGISTRATION_METHOD_ATTRIBUTE = "registration-method";
public static final String UNREGISTRATION_METHOD_ATTRIBUTE = "unregistration-method";
public static final String BIND_METHOD_ATTRIBUTE = "bind-method";
public static final String UNBIND_METHOD_ATTRIBUTE = "unbind-method";
public static final String KEY_TYPE_ATTRIBUTE = "key-type";
public static final String VALUE_TYPE_ATTRIBUTE = "value-type";
public static final String MEMBER_TYPE_ATTRIBUTE = "member-type";
public static final String SCOPE_ATTRIBUTE = "scope";
public static final String INIT_METHOD_ATTRIBUTE = "init-method";
public static final String DESTROY_METHOD_ATTRIBUTE = "destroy-method";
public static final String ACTIVATION_ATTRIBUTE = "activation";
public static final String FACTORY_REF_ATTRIBUTE = "factory-ref";
public static final String FACTORY_METHOD_ATTRIBUTE = "factory-method";
public static final String AUTO_EXPORT_DISABLED = "disabled";
public static final String AUTO_EXPORT_INTERFACES = "interfaces";
public static final String AUTO_EXPORT_CLASS_HIERARCHY = "class-hierarchy";
public static final String AUTO_EXPORT_ALL = "all-classes";
public static final String AUTO_EXPORT_DEFAULT = AUTO_EXPORT_DISABLED;
public static final String RANKING_DEFAULT = "0";
public static final String AVAILABILITY_MANDATORY = "mandatory";
public static final String AVAILABILITY_OPTIONAL = "optional";
public static final String AVAILABILITY_DEFAULT = AVAILABILITY_MANDATORY;
public static final String TIMEOUT_DEFAULT = "300000";
public static final String USE_SERVICE_OBJECT = "service-object";
public static final String USE_SERVICE_REFERENCE = "service-reference";
public static final String ACTIVATION_EAGER = "eager";
public static final String ACTIVATION_LAZY = "lazy";
public static final String ACTIVATION_DEFAULT = ACTIVATION_EAGER;
private static final Logger LOGGER = LoggerFactory.getLogger(Parser.class);
private static DocumentBuilderFactory documentBuilderFactory;
private List<Document> documents = new ArrayList<Document>();
private ComponentDefinitionRegistry registry;
private NamespaceHandlerRegistry.NamespaceHandlerSet handlers;
private String idPrefix = "component-";
private Set<String> ids = new HashSet<String>();
private int idCounter;
private String defaultTimeout;
private String defaultAvailability;
private String defaultActivation;
private Set<URI> namespaces;
public Parser() {
}
public Parser(String idPrefix) {
this.idPrefix = idPrefix;
}
/**
* Parse an input stream for blueprint xml.
* @param inputStream The data to parse. The caller is responsible for closing the stream afterwards.
* @throws Exception
*/
public void parse(InputStream inputStream) throws Exception {
InputSource inputSource = new InputSource(inputStream);
DocumentBuilder builder = getDocumentBuilderFactory().newDocumentBuilder();
Document doc = builder.parse(inputSource);
documents.add(doc);
}
/**
* Parse blueprint xml referred to by a list of URLs
* @param urls URLs to blueprint xml to parse
* @throws Exception
*/
public void parse(List<URL> urls) throws Exception {
// Create document builder factory
// Load documents
for (URL url : urls) {
InputStream inputStream = url.openStream();
try {
parse (inputStream);
} finally {
inputStream.close();
}
}
}
public Set<URI> getNamespaces() {
if (this.namespaces == null) {
if (documents == null) {
throw new IllegalStateException("Documents should be parsed before retrieving required namespaces");
}
Set<URI> namespaces = new LinkedHashSet<URI>();
for (Document doc : documents) {
findNamespaces(namespaces, doc);
}
this.namespaces = namespaces;
}
return this.namespaces;
}
private void findNamespaces(Set<URI> namespaces, Node node) {
if (node instanceof Element || node instanceof Attr) {
String ns = node.getNamespaceURI();
if (ns != null && !isBlueprintNamespace(ns) && !isIgnorableAttributeNamespace(ns)) {
namespaces.add(URI.create(ns));
}else if ( ns == null && //attributes from blueprint are unqualified as per schema.
node instanceof Attr &&
SCOPE_ATTRIBUTE.equals(node.getNodeName()) &&
((Attr)node).getOwnerElement() != null && //should never occur from parsed doc.
BLUEPRINT_NAMESPACE.equals(((Attr)node).getOwnerElement().getNamespaceURI()) &&
BEAN_ELEMENT.equals(((Attr)node).getOwnerElement().getLocalName()) ){
//Scope attribute is special case, as may contain namespace usage within its value.
URI scopeNS = getNamespaceForAttributeValue(node);
if(scopeNS!=null){
namespaces.add(scopeNS);
}
}
}
NamedNodeMap nnm = node.getAttributes();
if(nnm!=null){
for(int i = 0; i< nnm.getLength() ; i++){
findNamespaces(namespaces, nnm.item(i));
}
}
NodeList nl = node.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
findNamespaces(namespaces, nl.item(i));
}
}
public void populate(NamespaceHandlerRegistry.NamespaceHandlerSet handlers,
ComponentDefinitionRegistry registry) {
this.handlers = handlers;
this.registry = registry;
if (this.documents == null) {
throw new IllegalStateException("Documents should be parsed before populating the registry");
}
// Parse components
for (Document doc : this.documents) {
loadComponents(doc);
}
}
public void validate(Schema schema) {
try {
Validator validator = schema.newValidator();
for (Document doc : this.documents) {
validator.validate(new DOMSource(doc));
}
} catch (Exception e) {
throw new ComponentDefinitionException("Unable to validate xml", e);
}
}
private void loadComponents(Document doc) {
defaultTimeout = TIMEOUT_DEFAULT;
defaultAvailability = AVAILABILITY_DEFAULT;
defaultActivation = ACTIVATION_DEFAULT;
Element root = doc.getDocumentElement();
if (!isBlueprintNamespace(root.getNamespaceURI()) ||
!nodeNameEquals(root, BLUEPRINT_ELEMENT)) {
throw new ComponentDefinitionException("Root element must be {" + BLUEPRINT_NAMESPACE + "}" + BLUEPRINT_ELEMENT + " element");
}
// Parse global attributes
if (root.hasAttribute(DEFAULT_ACTIVATION_ATTRIBUTE)) {
defaultActivation = root.getAttribute(DEFAULT_ACTIVATION_ATTRIBUTE);
}
if (root.hasAttribute(DEFAULT_TIMEOUT_ATTRIBUTE)) {
defaultTimeout = root.getAttribute(DEFAULT_TIMEOUT_ATTRIBUTE);
}
if (root.hasAttribute(DEFAULT_AVAILABILITY_ATTRIBUTE)) {
defaultAvailability = root.getAttribute(DEFAULT_AVAILABILITY_ATTRIBUTE);
}
// Parse custom attributes
NamedNodeMap attributes = root.getAttributes();
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
if (node instanceof Attr
&& node.getNamespaceURI() != null
&& !isBlueprintNamespace(node.getNamespaceURI())
&& !XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(node.getNamespaceURI())
&& XMLConstants.XMLNS_ATTRIBUTE.equals(node.getNodeName())) {
decorateCustomNode(node, null);
}
}
}
// Parse elements
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element element = (Element) node;
String namespaceUri = element.getNamespaceURI();
if (isBlueprintNamespace(namespaceUri)) {
parseBlueprintElement(element);
} else {
Metadata component = parseCustomElement(element, null);
if (component != null) {
if (!(component instanceof ComponentMetadata)) {
throw new ComponentDefinitionException("Expected a ComponentMetadata to be returned when parsing element " + element.getNodeName());
}
registry.registerComponentDefinition((ComponentMetadata) component);
}
}
}
}
}
public <T> T parseElement(Class<T> type, ComponentMetadata enclosingComponent, Element element) {
if (BeanArgument.class.isAssignableFrom(type)) {
return type.cast(parseBeanArgument(enclosingComponent, element));
} else if (BeanProperty.class.isAssignableFrom(type)) {
return type.cast(parseBeanProperty(enclosingComponent, element));
} else if (MapEntry.class.isAssignableFrom(type)) {
return type.cast(parseMapEntry(element, enclosingComponent, null, null));
} else if (MapMetadata.class.isAssignableFrom(type)) {
return type.cast(parseMap(element, enclosingComponent));
} else if (BeanMetadata.class.isAssignableFrom(type)) {
return type.cast(parseBeanMetadata(element, false));
} else if (NullMetadata.class.isAssignableFrom(type)) {
return type.cast(NullMetadata.NULL);
} else if (CollectionMetadata.class.isAssignableFrom(type)) {
return type.cast(parseCollection(Collection.class, element, enclosingComponent));
} else if (PropsMetadata.class.isAssignableFrom(type)) {
return type.cast(parseProps(element));
} else if (ReferenceMetadata.class.isAssignableFrom(type)) {
return type.cast(parseReference(element, enclosingComponent == null));
} else if (ReferenceListMetadata.class.isAssignableFrom(type)) {
return type.cast(parseRefList(element, enclosingComponent == null));
} else if (IdRefMetadata.class.isAssignableFrom(type)) {
return type.cast(parseIdRef(element));
} else if (RefMetadata.class.isAssignableFrom(type)) {
return type.cast(parseRef(element));
} else if (ValueMetadata.class.isAssignableFrom(type)) {
return type.cast(parseValue(element, null));
} else if (ReferenceListener.class.isAssignableFrom(type)) {
return type.cast(parseServiceListener(element, enclosingComponent));
} else {
throw new ComponentDefinitionException("Unknown type to parse element: " + type.getName());
}
}
private void parseBlueprintElement(Element element) {
if (nodeNameEquals(element, DESCRIPTION_ELEMENT)) {
// Ignore description
} else if (nodeNameEquals(element, TYPE_CONVERTERS_ELEMENT)) {
parseTypeConverters(element);
} else if (nodeNameEquals(element, BEAN_ELEMENT)) {
ComponentMetadata component = parseBeanMetadata(element, true);
registry.registerComponentDefinition(component);
} else if (nodeNameEquals(element, SERVICE_ELEMENT)) {
ComponentMetadata service = parseService(element, true);
registry.registerComponentDefinition(service);
} else if (nodeNameEquals(element, REFERENCE_ELEMENT)) {
ComponentMetadata reference = parseReference(element, true);
registry.registerComponentDefinition(reference);
} else if (nodeNameEquals(element, REFERENCE_LIST_ELEMENT) ) {
ComponentMetadata references = parseRefList(element, true);
registry.registerComponentDefinition(references);
} else {
throw new ComponentDefinitionException("Unknown element " + element.getNodeName() + " in namespace " + BLUEPRINT_NAMESPACE);
}
}
private void parseTypeConverters(Element element) {
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
Object target = null;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, BEAN_ELEMENT)) {
target = parseBeanMetadata(e, true);
} else if (nodeNameEquals(e, REF_ELEMENT)) {
String componentName = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
target = new RefMetadataImpl(componentName);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
target = parseReference(e, true);
}
} else {
target = parseCustomElement(e, null);
}
if (!(target instanceof Target)) {
throw new ComponentDefinitionException("Metadata parsed for element " + e.getNodeName() + " can not be used as a type converter");
}
registry.registerTypeConverter((Target) target);
}
}
}
/**
* Takes an Attribute Node containing a namespace prefix qualified attribute value, and resolves the namespace using the DOM Node.<br>
*
* @param attr The DOM Node with the qualified attribute value.
* @return The URI if one is resolvable, or null if the attr is null, or not namespace prefixed. (or not a DOM Attribute Node)
* @throws ComponentDefinitonException if the namespace prefix in the attribute value cannot be resolved.
*/
private URI getNamespaceForAttributeValue(Node attrNode){
URI uri = null;
if(attrNode!=null && (attrNode instanceof Attr)){
Attr attr = (Attr)attrNode;
String attrValue = attr.getValue();
if(attrValue!=null && attrValue.indexOf(":")!=-1){
String parts[] = attrValue.split(":");
String uriStr = attr.getOwnerElement().lookupNamespaceURI(parts[0]);
if(uriStr!=null){
uri = URI.create(uriStr);
}else{
throw new ComponentDefinitionException("Unsupported attribute namespace prefix "+parts[0]+" "+attr);
}
}
}
return uri;
}
/**
* Tests if a scope attribute value is a custom scope, and if so invokes
* the appropriate namespace handler, passing the blueprint scope node.
* <p>
* Currently this tests for custom scope by looking for the presence of
* a ':' char within the scope attribute value. This is valid as long as
* the blueprint schema continues to restrict that custom scopes should
* require that characters presence.
* <p>
*
* @param scope Value of scope attribute
* @param bean DOM element for bean associated to this scope
* @param cm Metadata for bean associated to this scope
* @return Metadata as processed by NS Handler.
* @throws ComponentDefinitionException if an undeclared prefix is used,
* if a namespace handler is unavailable for a resolved prefix,
* or if the resolved prefix results as the blueprint namespace.
*/
private ComponentMetadata handleCustomScope(Node scope, Element bean, ComponentMetadata metadata){
URI scopeNS = getNamespaceForAttributeValue(scope);
if(scopeNS!=null && !BLUEPRINT_NAMESPACE.equals(scopeNS)){
NamespaceHandler nsHandler = getNamespaceHandler(scopeNS);
ParserContextImpl context = new ParserContextImpl(this, registry, metadata, scope);
metadata = nsHandler.decorate(scope, metadata, context);
}else if(scopeNS!=null){
throw new ComponentDefinitionException("Custom scopes cannot use the blueprint namespace "+scope);
}
return metadata;
}
private ComponentMetadata parseBeanMetadata(Element element, boolean topElement) {
BeanMetadataImpl metadata = new BeanMetadataImpl();
if (topElement) {
metadata.setId(getId(element));
if (element.hasAttribute(SCOPE_ATTRIBUTE)) {
metadata.setScope(element.getAttribute(SCOPE_ATTRIBUTE));
if (metadata.getScope().equals(BeanMetadata.SCOPE_PROTOTYPE)) {
if (element.hasAttribute(ACTIVATION_ATTRIBUTE)) {
if (element.getAttribute(ACTIVATION_ATTRIBUTE).equals(ACTIVATION_EAGER)) {
throw new ComponentDefinitionException("A <bean> with a prototype scope can not have an eager activation");
}
}
metadata.setActivation(ComponentMetadata.ACTIVATION_LAZY);
} else {
metadata.setActivation(parseActivation(element));
}
} else {
metadata.setActivation(parseActivation(element));
}
} else {
metadata.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(CLASS_ATTRIBUTE)) {
metadata.setClassName(element.getAttribute(CLASS_ATTRIBUTE));
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
metadata.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
if (element.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
metadata.setInitMethod(element.getAttribute(INIT_METHOD_ATTRIBUTE));
}
if (element.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
metadata.setDestroyMethod(element.getAttribute(DESTROY_METHOD_ATTRIBUTE));
}
if (element.hasAttribute(FACTORY_REF_ATTRIBUTE)) {
metadata.setFactoryComponent(new RefMetadataImpl(element.getAttribute(FACTORY_REF_ATTRIBUTE)));
}
if (element.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
String factoryMethod = element.getAttribute(FACTORY_METHOD_ATTRIBUTE);
metadata.setFactoryMethod(factoryMethod);
}
// Do some validation
if (metadata.getClassName() == null && metadata.getFactoryComponent() == null) {
throw new ComponentDefinitionException("Bean class or factory-ref must be specified");
}
if (metadata.getFactoryComponent() != null && metadata.getFactoryMethod() == null) {
throw new ComponentDefinitionException("factory-method is required when factory-component is set");
}
if (MetadataUtil.isPrototypeScope(metadata) && metadata.getDestroyMethod() != null) {
throw new ComponentDefinitionException("destroy-method must not be set for a <bean> with a prototype scope");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(node.getNamespaceURI())) {
if (nodeNameEquals(node, ARGUMENT_ELEMENT)) {
metadata.addArgument(parseBeanArgument(metadata, e));
} else if (nodeNameEquals(node, PROPERTY_ELEMENT)) {
metadata.addProperty(parseBeanProperty(metadata, e));
}
}
}
}
MetadataUtil.validateBeanArguments(metadata.getArguments());
ComponentMetadata m = metadata;
// Parse custom scopes
m = handleCustomScope(element.getAttributeNode(SCOPE_ATTRIBUTE), element, m);
// Parse custom attributes
m = handleCustomAttributes(element.getAttributes(), m);
// Parse custom elements;
m = handleCustomElements(element, m);
return m;
}
public BeanProperty parseBeanProperty(ComponentMetadata enclosingComponent, Element element) {
String name = element.hasAttribute(NAME_ATTRIBUTE) ? element.getAttribute(NAME_ATTRIBUTE) : null;
Metadata value = parseArgumentOrPropertyValue(element, enclosingComponent);
return new BeanPropertyImpl(name, value);
}
private BeanArgument parseBeanArgument(ComponentMetadata enclosingComponent, Element element) {
int index = element.hasAttribute(INDEX_ATTRIBUTE) ? Integer.parseInt(element.getAttribute(INDEX_ATTRIBUTE)) : -1;
String type = element.hasAttribute(TYPE_ATTRIBUTE) ? element.getAttribute(TYPE_ATTRIBUTE) : null;
Metadata value = parseArgumentOrPropertyValue(element, enclosingComponent);
return new BeanArgumentImpl(value, type, index);
}
private ComponentMetadata parseService(Element element, boolean topElement) {
ServiceMetadataImpl service = new ServiceMetadataImpl();
boolean hasInterfaceNameAttribute = false;
if (topElement) {
service.setId(getId(element));
service.setActivation(parseActivation(element));
} else {
service.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(INTERFACE_ATTRIBUTE)) {
service.setInterfaceNames(Collections.singletonList(element.getAttribute(INTERFACE_ATTRIBUTE)));
hasInterfaceNameAttribute = true;
}
if (element.hasAttribute(REF_ATTRIBUTE)) {
service.setServiceComponent(new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE)));
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
service.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
String autoExport = element.hasAttribute(AUTO_EXPORT_ATTRIBUTE) ? element.getAttribute(AUTO_EXPORT_ATTRIBUTE) : AUTO_EXPORT_DEFAULT;
if (AUTO_EXPORT_DISABLED.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_DISABLED);
} else if (AUTO_EXPORT_INTERFACES.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_INTERFACES);
} else if (AUTO_EXPORT_CLASS_HIERARCHY.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_CLASS_HIERARCHY);
} else if (AUTO_EXPORT_ALL.equals(autoExport)) {
service.setAutoExport(ServiceMetadata.AUTO_EXPORT_ALL_CLASSES);
} else {
throw new ComponentDefinitionException("Illegal value (" + autoExport + ") for " + AUTO_EXPORT_ATTRIBUTE + " attribute");
}
String ranking = element.hasAttribute(RANKING_ATTRIBUTE) ? element.getAttribute(RANKING_ATTRIBUTE) : RANKING_DEFAULT;
try {
service.setRanking(Integer.parseInt(ranking));
} catch (NumberFormatException e) {
throw new ComponentDefinitionException("Attribute " + RANKING_ATTRIBUTE + " must be a valid integer (was: " + ranking + ")");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, INTERFACES_ELEMENT)) {
if (hasInterfaceNameAttribute) {
throw new ComponentDefinitionException("Only one of " + INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must be used");
}
service.setInterfaceNames(parseInterfaceNames(e));
} else if (nodeNameEquals(e, SERVICE_PROPERTIES_ELEMENT)) {
List<MapEntry> entries = parseServiceProperties(e, service).getEntries();
service.setServiceProperties(entries);
} else if (nodeNameEquals(e, REGISTRATION_LISTENER_ELEMENT)) {
service.addRegistrationListener(parseRegistrationListener(e, service));
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
service.setServiceComponent((Target) parseBeanMetadata(e, false));
} else if (nodeNameEquals(e, REF_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
service.setServiceComponent(new RefMetadataImpl(component));
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (service.getServiceComponent() != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element can be set");
}
service.setServiceComponent((Target) parseReference(e, false));
}
}
}
}
// Check service
if (service.getServiceComponent() == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + BEAN_ELEMENT + " element, " + REFERENCE_ELEMENT + " element or " + REF_ELEMENT + " element must be set");
}
// Check interface
if (service.getAutoExport() == ServiceMetadata.AUTO_EXPORT_DISABLED && service.getInterfaces().isEmpty()) {
throw new ComponentDefinitionException(INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must be set when " + AUTO_EXPORT_ATTRIBUTE + " is set to " + AUTO_EXPORT_DISABLED);
}
// Check for non-disabled auto-exports and interfaces
if (service.getAutoExport() != ServiceMetadata.AUTO_EXPORT_DISABLED && !service.getInterfaces().isEmpty()) {
throw new ComponentDefinitionException(INTERFACE_ATTRIBUTE + " attribute or " + INTERFACES_ELEMENT + " element must not be set when " + AUTO_EXPORT_ATTRIBUTE + " is set to anything else than " + AUTO_EXPORT_DISABLED);
}
ComponentMetadata s = service;
// Parse custom attributes
s = handleCustomAttributes(element.getAttributes(), s);
// Parse custom elements;
s = handleCustomElements(element, s);
return s;
}
private CollectionMetadata parseArray(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(Object[].class, element, enclosingComponent);
}
private CollectionMetadata parseList(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(List.class, element, enclosingComponent);
}
private CollectionMetadata parseSet(Element element, ComponentMetadata enclosingComponent) {
return parseCollection(Set.class, element, enclosingComponent);
}
private CollectionMetadata parseCollection(Class collectionType, Element element, ComponentMetadata enclosingComponent) {
// Parse attributes
String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
// Parse elements
List<Metadata> list = new ArrayList<Metadata>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Metadata val = parseValueGroup((Element) node, enclosingComponent, null, true);
list.add(val);
}
}
return new CollectionMetadataImpl(collectionType, valueType, list);
}
public PropsMetadata parseProps(Element element) {
// Parse elements
List<MapEntry> entries = new ArrayList<MapEntry>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI()) && nodeNameEquals(e, PROP_ELEMENT)) {
entries.add(parseProperty(e));
}
}
}
return new PropsMetadataImpl(entries);
}
private MapEntry parseProperty(Element element) {
// Parse attributes
if (!element.hasAttribute(KEY_ATTRIBUTE)) {
throw new ComponentDefinitionException(KEY_ATTRIBUTE + " attribute is required");
}
String value = null;
if (element.hasAttribute(VALUE_ATTRIBUTE)) {
value = element.getAttribute(VALUE_ATTRIBUTE);
} else {
value = getTextValue(element);
}
String key = element.getAttribute(KEY_ATTRIBUTE);
return new MapEntryImpl(new ValueMetadataImpl(key), new ValueMetadataImpl(value));
}
public MapMetadata parseMap(Element element, ComponentMetadata enclosingComponent) {
// Parse attributes
String keyType = element.hasAttribute(KEY_TYPE_ATTRIBUTE) ? element.getAttribute(KEY_TYPE_ATTRIBUTE) : null;
String valueType = element.hasAttribute(VALUE_TYPE_ATTRIBUTE) ? element.getAttribute(VALUE_TYPE_ATTRIBUTE) : null;
// Parse elements
List<MapEntry> entries = new ArrayList<MapEntry>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, ENTRY_ELEMENT)) {
entries.add(parseMapEntry(e, enclosingComponent, null, null));
}
}
}
return new MapMetadataImpl(keyType, valueType, entries);
}
private MapEntry parseMapEntry(Element element, ComponentMetadata enclosingComponent, String keyType, String valueType) {
// Parse attributes
String key = element.hasAttribute(KEY_ATTRIBUTE) ? element.getAttribute(KEY_ATTRIBUTE) : null;
String keyRef = element.hasAttribute(KEY_REF_ATTRIBUTE) ? element.getAttribute(KEY_REF_ATTRIBUTE) : null;
String value = element.hasAttribute(VALUE_ATTRIBUTE) ? element.getAttribute(VALUE_ATTRIBUTE) : null;
String valueRef = element.hasAttribute(VALUE_REF_ATTRIBUTE) ? element.getAttribute(VALUE_REF_ATTRIBUTE) : null;
// Parse elements
NonNullMetadata keyValue = null;
Metadata valValue = null;
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, KEY_ELEMENT)) {
keyValue = parseMapKeyEntry(e, enclosingComponent, keyType);
} else {
valValue = parseValueGroup(e, enclosingComponent, valueType, true);
}
}
}
// Check key
if (keyValue != null && (key != null || keyRef != null) || (keyValue == null && key == null && keyRef == null)) {
throw new ComponentDefinitionException("Only and only one of " + KEY_ATTRIBUTE + " attribute, " + KEY_REF_ATTRIBUTE + " attribute or " + KEY_ELEMENT + " element must be set");
} else if (keyValue == null && key != null) {
keyValue = new ValueMetadataImpl(key, keyType);
} else if (keyValue == null /*&& keyRef != null*/) {
keyValue = new RefMetadataImpl(keyRef);
}
// Check value
if (valValue != null && (value != null || valueRef != null) || (valValue == null && value == null && valueRef == null)) {
throw new ComponentDefinitionException("Only and only one of " + VALUE_ATTRIBUTE + " attribute, " + VALUE_REF_ATTRIBUTE + " attribute or sub element must be set");
} else if (valValue == null && value != null) {
valValue = new ValueMetadataImpl(value, valueType);
} else if (valValue == null /*&& valueRef != null*/) {
valValue = new RefMetadataImpl(valueRef);
}
return new MapEntryImpl(keyValue, valValue);
}
private NonNullMetadata parseMapKeyEntry(Element element, ComponentMetadata enclosingComponent, String keyType) {
NonNullMetadata keyValue = null;
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (keyValue != null) {
// TODO: throw an exception
}
keyValue = (NonNullMetadata) parseValueGroup(e, enclosingComponent, keyType, false);
break;
}
}
if (keyValue == null) {
// TODO: throw an exception
}
return keyValue;
}
public MapMetadata parseServiceProperties(Element element, ComponentMetadata enclosingComponent) {
// TODO: need to handle this better
MapMetadata map = parseMap(element, enclosingComponent);
handleCustomElements(element, enclosingComponent);
return map;
}
public RegistrationListener parseRegistrationListener(Element element, ComponentMetadata enclosingComponent) {
RegistrationListenerImpl listener = new RegistrationListenerImpl();
Metadata listenerComponent = null;
// Parse attributes
if (element.hasAttribute(REF_ATTRIBUTE)) {
listenerComponent = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
String registrationMethod = null;
if (element.hasAttribute(REGISTRATION_METHOD_ATTRIBUTE)) {
registrationMethod = element.getAttribute(REGISTRATION_METHOD_ATTRIBUTE);
listener.setRegistrationMethod(registrationMethod);
}
String unregistrationMethod = null;
if (element.hasAttribute(UNREGISTRATION_METHOD_ATTRIBUTE)) {
unregistrationMethod = element.getAttribute(UNREGISTRATION_METHOD_ATTRIBUTE);
listener.setUnregistrationMethod(unregistrationMethod);
}
if (registrationMethod == null && unregistrationMethod == null) {
throw new ComponentDefinitionException("One of " + REGISTRATION_METHOD_ATTRIBUTE + " or " + UNREGISTRATION_METHOD_ATTRIBUTE + " must be set");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REF_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
listenerComponent = new RefMetadataImpl(component);
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseBeanMetadata(e, false);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseReference(e, false);
} else if (nodeNameEquals(e, SERVICE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseService(e, false);
}
} else {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseCustomElement(e, enclosingComponent);
}
}
}
if (listenerComponent == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BEAN_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element must be set");
}
listener.setListenerComponent((Target) listenerComponent);
return listener;
}
private ComponentMetadata parseReference(Element element, boolean topElement) {
ReferenceMetadataImpl reference = new ReferenceMetadataImpl();
if (topElement) {
reference.setId(getId(element));
}
parseReference(element, reference, topElement);
String timeout = element.hasAttribute(TIMEOUT_ATTRIBUTE) ? element.getAttribute(TIMEOUT_ATTRIBUTE) : this.defaultTimeout;
try {
reference.setTimeout(Long.parseLong(timeout));
} catch (NumberFormatException e) {
throw new ComponentDefinitionException("Attribute " + TIMEOUT_ATTRIBUTE + " must be a valid long (was: " + timeout + ")");
}
ComponentMetadata r = reference;
// Parse custom attributes
r = handleCustomAttributes(element.getAttributes(), r);
// Parse custom elements;
r = handleCustomElements(element, r);
return r;
}
public String getDefaultTimeout() {
return defaultTimeout;
}
public String getDefaultAvailability() {
return defaultAvailability;
}
public String getDefaultActivation() {
return defaultActivation;
}
private ComponentMetadata parseRefList(Element element, boolean topElement) {
ReferenceListMetadataImpl references = new ReferenceListMetadataImpl();
if (topElement) {
references.setId(getId(element));
}
if (element.hasAttribute(MEMBER_TYPE_ATTRIBUTE)) {
String memberType = element.getAttribute(MEMBER_TYPE_ATTRIBUTE);
if (USE_SERVICE_OBJECT.equals(memberType)) {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_OBJECT);
} else if (USE_SERVICE_REFERENCE.equals(memberType)) {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_REFERENCE);
}
} else {
references.setMemberType(ReferenceListMetadata.USE_SERVICE_OBJECT);
}
parseReference(element, references, topElement);
ComponentMetadata r = references;
// Parse custom attributes
r = handleCustomAttributes(element.getAttributes(), r);
// Parse custom elements;
r = handleCustomElements(element, r);
return r;
}
private void parseReference(Element element, ServiceReferenceMetadataImpl reference, boolean topElement) {
// Parse attributes
if (topElement) {
reference.setActivation(parseActivation(element));
} else {
reference.setActivation(ComponentMetadata.ACTIVATION_LAZY);
}
if (element.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
reference.setDependsOn(parseList(element.getAttribute(DEPENDS_ON_ATTRIBUTE)));
}
if (element.hasAttribute(INTERFACE_ATTRIBUTE)) {
reference.setInterface(element.getAttribute(INTERFACE_ATTRIBUTE));
}
if (element.hasAttribute(FILTER_ATTRIBUTE)) {
reference.setFilter(element.getAttribute(FILTER_ATTRIBUTE));
}
if (element.hasAttribute(COMPONENT_NAME_ATTRIBUTE)) {
reference.setComponentName(element.getAttribute(COMPONENT_NAME_ATTRIBUTE));
}
String availability = element.hasAttribute(AVAILABILITY_ATTRIBUTE) ? element.getAttribute(AVAILABILITY_ATTRIBUTE) : defaultAvailability;
if (AVAILABILITY_MANDATORY.equals(availability)) {
reference.setAvailability(ServiceReferenceMetadata.AVAILABILITY_MANDATORY);
} else if (AVAILABILITY_OPTIONAL.equals(availability)) {
reference.setAvailability(ServiceReferenceMetadata.AVAILABILITY_OPTIONAL);
} else {
throw new ComponentDefinitionException("Illegal value for " + AVAILABILITY_ATTRIBUTE + " attribute: " + availability);
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REFERENCE_LISTENER_ELEMENT)) {
reference.addServiceListener(parseServiceListener(e, reference));
}
}
}
}
}
private ReferenceListener parseServiceListener(Element element, ComponentMetadata enclosingComponent) {
ReferenceListenerImpl listener = new ReferenceListenerImpl();
Metadata listenerComponent = null;
// Parse attributes
if (element.hasAttribute(REF_ATTRIBUTE)) {
listenerComponent = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
String bindMethodName = null;
String unbindMethodName = null;
if (element.hasAttribute(BIND_METHOD_ATTRIBUTE)) {
bindMethodName = element.getAttribute(BIND_METHOD_ATTRIBUTE);
listener.setBindMethod(bindMethodName);
}
if (element.hasAttribute(UNBIND_METHOD_ATTRIBUTE)) {
unbindMethodName = element.getAttribute(UNBIND_METHOD_ATTRIBUTE);
listener.setUnbindMethod(unbindMethodName);
}
if (bindMethodName == null && unbindMethodName == null) {
throw new ComponentDefinitionException("One of " + BIND_METHOD_ATTRIBUTE + " or " + UNBIND_METHOD_ATTRIBUTE + " must be set");
}
// Parse elements
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(e.getNamespaceURI())) {
if (nodeNameEquals(e, REF_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
String component = e.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
listenerComponent = new RefMetadataImpl(component);
} else if (nodeNameEquals(e, BEAN_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseBeanMetadata(e, false);
} else if (nodeNameEquals(e, REFERENCE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseReference(e, false);
} else if (nodeNameEquals(e, SERVICE_ELEMENT)) {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseService(e, false);
}
} else {
if (listenerComponent != null) {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element can be set");
}
listenerComponent = parseCustomElement(e, enclosingComponent);
}
}
}
if (listenerComponent == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + REF_ELEMENT + ", " + BLUEPRINT_ELEMENT + ", " + REFERENCE_ELEMENT + ", " + SERVICE_ELEMENT + " or custom element must be set");
}
listener.setListenerComponent((Target) listenerComponent);
return listener;
}
public List<String> parseInterfaceNames(Element element) {
List<String> interfaceNames = new ArrayList<String>();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (nodeNameEquals(e, VALUE_ELEMENT)) {
String v = getTextValue(e).trim();
if (interfaceNames.contains(v)) {
throw new ComponentDefinitionException("The element " + INTERFACES_ELEMENT + " should not contain the same interface twice");
}
interfaceNames.add(getTextValue(e));
} else {
throw new ComponentDefinitionException("Unsupported element " + e.getNodeName() + " inside an " + INTERFACES_ELEMENT + " element");
}
}
}
return interfaceNames;
}
private Metadata parseArgumentOrPropertyValue(Element element, ComponentMetadata enclosingComponent) {
Metadata [] values = new Metadata[3];
if (element.hasAttribute(REF_ATTRIBUTE)) {
values[0] = new RefMetadataImpl(element.getAttribute(REF_ATTRIBUTE));
}
if (element.hasAttribute(VALUE_ATTRIBUTE)) {
values[1] = new ValueMetadataImpl(element.getAttribute(VALUE_ATTRIBUTE));
}
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element e = (Element) node;
if (isBlueprintNamespace(node.getNamespaceURI()) && nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
// Ignore description elements
} else {
values[2] = parseValueGroup(e, enclosingComponent, null, true);
break;
}
}
}
Metadata value = null;
for (Metadata v : values) {
if (v != null) {
if (value == null) {
value = v;
} else {
throw new ComponentDefinitionException("Only one of " + REF_ATTRIBUTE + " attribute, " + VALUE_ATTRIBUTE + " attribute or sub element must be set");
}
}
}
if (value == null) {
throw new ComponentDefinitionException("One of " + REF_ATTRIBUTE + " attribute, " + VALUE_ATTRIBUTE + " attribute or sub element must be set");
}
return value;
}
private Metadata parseValueGroup(Element element, ComponentMetadata enclosingComponent, String collectionType, boolean allowNull) {
if (isBlueprintNamespace(element.getNamespaceURI())) {
if (nodeNameEquals(element, BEAN_ELEMENT)) {
return parseBeanMetadata(element, false);
} else if (nodeNameEquals(element, REFERENCE_ELEMENT)) {
return parseReference(element, false);
} else if (nodeNameEquals(element, SERVICE_ELEMENT)) {
return parseService(element, false);
} else if (nodeNameEquals(element, REFERENCE_LIST_ELEMENT) ) {
return parseRefList(element, false);
} else if (nodeNameEquals(element, NULL_ELEMENT) && allowNull) {
return NullMetadata.NULL;
} else if (nodeNameEquals(element, VALUE_ELEMENT)) {
return parseValue(element, collectionType);
} else if (nodeNameEquals(element, REF_ELEMENT)) {
return parseRef(element);
} else if (nodeNameEquals(element, IDREF_ELEMENT)) {
return parseIdRef(element);
} else if (nodeNameEquals(element, LIST_ELEMENT)) {
return parseList(element, enclosingComponent);
} else if (nodeNameEquals(element, SET_ELEMENT)) {
return parseSet(element, enclosingComponent);
} else if (nodeNameEquals(element, MAP_ELEMENT)) {
return parseMap(element, enclosingComponent);
} else if (nodeNameEquals(element, PROPS_ELEMENT)) {
return parseProps(element);
} else if (nodeNameEquals(element, ARRAY_ELEMENT)) {
return parseArray(element, enclosingComponent);
} else {
throw new ComponentDefinitionException("Unknown blueprint element " + element.getNodeName());
}
} else {
return parseCustomElement(element, enclosingComponent);
}
}
private ValueMetadata parseValue(Element element, String collectionType) {
String type = null;
if (element.hasAttribute(TYPE_ATTRIBUTE)) {
type = element.getAttribute(TYPE_ATTRIBUTE);
} else {
type = collectionType;
}
return new ValueMetadataImpl(getTextValue(element), type);
}
private RefMetadata parseRef(Element element) {
String component = element.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + REF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
return new RefMetadataImpl(component);
}
private Metadata parseIdRef(Element element) {
String component = element.getAttribute(COMPONENT_ID_ATTRIBUTE);
if (component == null || component.length() == 0) {
throw new ComponentDefinitionException("Element " + IDREF_ELEMENT + " must have a valid " + COMPONENT_ID_ATTRIBUTE + " attribute");
}
return new IdRefMetadataImpl(component);
}
private int parseActivation(Element element) {
String initialization = element.hasAttribute(ACTIVATION_ATTRIBUTE) ? element.getAttribute(ACTIVATION_ATTRIBUTE) : defaultActivation;
if (ACTIVATION_EAGER.equals(initialization)) {
return ComponentMetadata.ACTIVATION_EAGER;
} else if (ACTIVATION_LAZY.equals(initialization)) {
return ComponentMetadata.ACTIVATION_LAZY;
} else {
throw new ComponentDefinitionException("Attribute " + ACTIVATION_ATTRIBUTE + " must be equal to " + ACTIVATION_EAGER + " or " + ACTIVATION_LAZY);
}
}
private ComponentMetadata handleCustomAttributes(NamedNodeMap attributes, ComponentMetadata enclosingComponent) {
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
//attr is custom if it has a namespace, and it isnt blueprint, or the xmlns ns.
//blueprint ns would be an error, as blueprint attrs are unqualified.
if (node instanceof Attr &&
node.getNamespaceURI() != null &&
!isBlueprintNamespace(node.getNamespaceURI()) &&
!isIgnorableAttributeNamespace(node.getNamespaceURI()) ) {
enclosingComponent = decorateCustomNode(node, enclosingComponent);
}
}
}
return enclosingComponent;
}
private ComponentMetadata handleCustomElements(Element element, ComponentMetadata enclosingComponent) {
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
if (!isBlueprintNamespace(node.getNamespaceURI())) {
enclosingComponent = decorateCustomNode(node, enclosingComponent);
}
}
}
return enclosingComponent;
}
private ComponentMetadata decorateCustomNode(Node node, ComponentMetadata enclosingComponent) {
NamespaceHandler handler = getNamespaceHandler(node);
ParserContextImpl context = new ParserContextImpl(this, registry, enclosingComponent, node);
return handler.decorate(node, enclosingComponent, context);
}
private Metadata parseCustomElement(Element element, ComponentMetadata enclosingComponent) {
NamespaceHandler handler = getNamespaceHandler(element);
ParserContextImpl context = new ParserContextImpl(this, registry, enclosingComponent, element);
return handler.parse(element, context);
}
private NamespaceHandler getNamespaceHandler(Node node) {
URI ns = URI.create(node.getNamespaceURI());
NamespaceHandler handler = getNamespaceHandler(ns);
return handler;
}
private NamespaceHandler getNamespaceHandler(URI uri) {
if (handlers == null) {
throw new ComponentDefinitionException("Unsupported node (namespace handler registry is not set): " + uri);
}
NamespaceHandler handler = this.handlers.getNamespaceHandler(uri);
if (handler == null) {
throw new ComponentDefinitionException("Unsupported node namespace: " + uri);
}
return handler;
}
public String generateId() {
String id;
do {
id = "." + idPrefix + ++idCounter;
} while (ids.contains(id));
ids.add(id);
return id;
}
public String getId(Element element) {
String id;
if (element.hasAttribute(ID_ATTRIBUTE)) {
id = element.getAttribute(ID_ATTRIBUTE);
ids.add(id);
} else {
id = generateId();
}
return id;
}
public static boolean isBlueprintNamespace(String ns) {
return BLUEPRINT_NAMESPACE.equals(ns);
}
/**
* Test if this namespace uri does not require a Namespace Handler.<p>
* <li> XMLConstants.RELAXNG_NS_URI
* <li> XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI
* <li> XMLConstants.W3C_XML_SCHEMA_NS_URI
* <li> XMLConstants.W3C_XPATH_DATATYPE_NS_URI
* <li> XMLConstants.W3C_XPATH_DATATYPE_NS_URI
* <li> XMLConstants.XML_DTD_NS_URI
* <li> XMLConstants.XML_NS_URI
* <li> XMLConstants.XMLNS_ATTRIBUTE_NS_URI
* @param ns URI to be tested.
* @return true if the uri does not require a namespace handler.
*/
public static boolean isIgnorableAttributeNamespace(String ns) {
return XMLConstants.RELAXNG_NS_URI.equals(ns) ||
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI.equals(ns) ||
XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(ns) ||
XMLConstants.W3C_XPATH_DATATYPE_NS_URI.equals(ns) ||
XMLConstants.W3C_XPATH_DATATYPE_NS_URI.equals(ns) ||
XMLConstants.XML_DTD_NS_URI.equals(ns) ||
XMLConstants.XML_NS_URI.equals(ns) ||
XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(ns);
}
private static boolean nodeNameEquals(Node node, String name) {
return (name.equals(node.getNodeName()) || name.equals(node.getLocalName()));
}
private static List<String> parseList(String list) {
String[] items = list.split(" ");
List<String> set = new ArrayList<String>();
for (String item : items) {
item = item.trim();
if (item.length() > 0) {
set.add(item);
}
}
return set;
}
private static String getTextValue(Element element) {
StringBuffer value = new StringBuffer();
NodeList nl = element.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
value.append(item.getNodeValue());
}
}
return value.toString();
}
private static DocumentBuilderFactory getDocumentBuilderFactory() {
if (documentBuilderFactory == null) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
documentBuilderFactory = dbf;
}
return documentBuilderFactory;
}
}
| minor code and javadoc cleanup, no semantic change
git-svn-id: 212869a37fe990abe2323f86150f3c4d5a6279c2@908306 13f79535-47bb-0310-9956-ffa450edef68
| blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/Parser.java | minor code and javadoc cleanup, no semantic change | <ide><path>lueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/Parser.java
<ide> import javax.xml.transform.dom.DOMSource;
<ide> import javax.xml.validation.Schema;
<ide> import javax.xml.validation.Validator;
<del>
<ide> import org.apache.aries.blueprint.ComponentDefinitionRegistry;
<ide> import org.apache.aries.blueprint.NamespaceHandler;
<ide> import org.apache.aries.blueprint.reflect.BeanArgumentImpl;
<ide> import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
<ide> import org.osgi.service.blueprint.reflect.Target;
<ide> import org.osgi.service.blueprint.reflect.ValueMetadata;
<del>import org.slf4j.Logger;
<del>import org.slf4j.LoggerFactory;
<ide> import org.w3c.dom.Attr;
<ide> import org.w3c.dom.CharacterData;
<ide> import org.w3c.dom.Comment;
<ide> public static final String ACTIVATION_LAZY = "lazy";
<ide> public static final String ACTIVATION_DEFAULT = ACTIVATION_EAGER;
<ide>
<del> private static final Logger LOGGER = LoggerFactory.getLogger(Parser.class);
<del>
<ide> private static DocumentBuilderFactory documentBuilderFactory;
<ide>
<del> private List<Document> documents = new ArrayList<Document>();
<add> private final List<Document> documents = new ArrayList<Document>();
<ide> private ComponentDefinitionRegistry registry;
<ide> private NamespaceHandlerRegistry.NamespaceHandlerSet handlers;
<ide> private String idPrefix = "component-";
<ide> /**
<ide> * Parse an input stream for blueprint xml.
<ide> * @param inputStream The data to parse. The caller is responsible for closing the stream afterwards.
<del> * @throws Exception
<add> * @throws Exception on parse error
<ide> */
<ide> public void parse(InputStream inputStream) throws Exception {
<ide> InputSource inputSource = new InputSource(inputStream);
<ide> /**
<ide> * Parse blueprint xml referred to by a list of URLs
<ide> * @param urls URLs to blueprint xml to parse
<del> * @throws Exception
<add> * @throws Exception on parse error
<ide> */
<ide> public void parse(List<URL> urls) throws Exception {
<ide> // Create document builder factory
<ide>
<ide> public Set<URI> getNamespaces() {
<ide> if (this.namespaces == null) {
<del> if (documents == null) {
<del> throw new IllegalStateException("Documents should be parsed before retrieving required namespaces");
<del> }
<ide> Set<URI> namespaces = new LinkedHashSet<URI>();
<ide> for (Document doc : documents) {
<ide> findNamespaces(namespaces, doc);
<ide> /**
<ide> * Takes an Attribute Node containing a namespace prefix qualified attribute value, and resolves the namespace using the DOM Node.<br>
<ide> *
<del> * @param attr The DOM Node with the qualified attribute value.
<add> * @param attrNode The DOM Node with the qualified attribute value.
<ide> * @return The URI if one is resolvable, or null if the attr is null, or not namespace prefixed. (or not a DOM Attribute Node)
<del> * @throws ComponentDefinitonException if the namespace prefix in the attribute value cannot be resolved.
<add> * @throws ComponentDefinitionException if the namespace prefix in the attribute value cannot be resolved.
<ide> */
<del> private URI getNamespaceForAttributeValue(Node attrNode){
<add> private URI getNamespaceForAttributeValue(Node attrNode) throws ComponentDefinitionException {
<ide> URI uri = null;
<ide> if(attrNode!=null && (attrNode instanceof Attr)){
<ide> Attr attr = (Attr)attrNode;
<ide> *
<ide> * @param scope Value of scope attribute
<ide> * @param bean DOM element for bean associated to this scope
<del> * @param cm Metadata for bean associated to this scope
<ide> * @return Metadata as processed by NS Handler.
<ide> * @throws ComponentDefinitionException if an undeclared prefix is used,
<ide> * if a namespace handler is unavailable for a resolved prefix,
<ide> */
<ide> private ComponentMetadata handleCustomScope(Node scope, Element bean, ComponentMetadata metadata){
<ide> URI scopeNS = getNamespaceForAttributeValue(scope);
<del> if(scopeNS!=null && !BLUEPRINT_NAMESPACE.equals(scopeNS)){
<add> if(scopeNS!=null && !BLUEPRINT_NAMESPACE.equals(scopeNS.toString())){
<ide> NamespaceHandler nsHandler = getNamespaceHandler(scopeNS);
<ide> ParserContextImpl context = new ParserContextImpl(this, registry, metadata, scope);
<ide> metadata = nsHandler.decorate(scope, metadata, context);
<ide> if (!element.hasAttribute(KEY_ATTRIBUTE)) {
<ide> throw new ComponentDefinitionException(KEY_ATTRIBUTE + " attribute is required");
<ide> }
<del> String value = null;
<add> String value;
<ide> if (element.hasAttribute(VALUE_ATTRIBUTE)) {
<ide> value = element.getAttribute(VALUE_ATTRIBUTE);
<ide> } else {
<ide> }
<ide>
<ide> private ValueMetadata parseValue(Element element, String collectionType) {
<del> String type = null;
<add> String type;
<ide> if (element.hasAttribute(TYPE_ATTRIBUTE)) {
<ide> type = element.getAttribute(TYPE_ATTRIBUTE);
<ide> } else {
<ide>
<ide> private NamespaceHandler getNamespaceHandler(Node node) {
<ide> URI ns = URI.create(node.getNamespaceURI());
<del> NamespaceHandler handler = getNamespaceHandler(ns);
<del> return handler;
<add> return getNamespaceHandler(ns);
<ide> }
<ide>
<ide> private NamespaceHandler getNamespaceHandler(URI uri) { |
|
Java | epl-1.0 | a2f26e01d27685aaf9059438c58d857c80d56cd2 | 0 | rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse | /*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.eclipse.core.model.loader;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.isInCeylonClassesOutputFolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.WorkingCopyOwner;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.ISourceType;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
import org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons;
import org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.core.ClassFile;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jdt.internal.core.SourceTypeElementInfo;
import org.eclipse.jdt.internal.core.search.BasicSearchEngine;
import com.redhat.ceylon.cmr.api.ArtifactResult;
import com.redhat.ceylon.compiler.java.loader.TypeFactory;
import com.redhat.ceylon.compiler.java.util.Timer;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.loader.AbstractModelLoader;
import com.redhat.ceylon.compiler.loader.JDKPackageList;
import com.redhat.ceylon.compiler.loader.SourceDeclarationVisitor;
import com.redhat.ceylon.compiler.loader.TypeParser;
import com.redhat.ceylon.compiler.loader.mirror.ClassMirror;
import com.redhat.ceylon.compiler.loader.mirror.MethodMirror;
import com.redhat.ceylon.compiler.loader.model.LazyClass;
import com.redhat.ceylon.compiler.loader.model.LazyInterface;
import com.redhat.ceylon.compiler.loader.model.LazyMethod;
import com.redhat.ceylon.compiler.loader.model.LazyModule;
import com.redhat.ceylon.compiler.loader.model.LazyPackage;
import com.redhat.ceylon.compiler.loader.model.LazyValue;
import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.ExternalUnit;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Modules;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.core.model.CeylonDeclaration;
/**
* A model loader which uses the JDT model.
*
* @author David Festal <[email protected]>
*/
public class JDTModelLoader extends AbstractModelLoader {
private IJavaProject javaProject;
private CompilerOptions compilerOptions;
private ProblemReporter problemReporter;
private LookupEnvironment lookupEnvironment;
private boolean mustResetLookupEnvironment = false;
private Map<String, Declaration> languageModuledeclarations;
public JDTModelLoader(final ModuleManager moduleManager, final Modules modules){
this.moduleManager = moduleManager;
this.modules = modules;
javaProject = ((JDTModuleManager)moduleManager).getJavaProject();
compilerOptions = new CompilerOptions(javaProject.getOptions(true));
compilerOptions.ignoreMethodBodies = true;
compilerOptions.storeAnnotations = true;
problemReporter = new ProblemReporter(
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
compilerOptions,
new DefaultProblemFactory());
internalCreate();
}
private void internalCreate() {
this.languageModuledeclarations = new HashMap<String, Declaration>();
this.typeFactory = new TypeFactory(moduleManager.getContext()) {
@Override
public Package getPackage() {
synchronized (JDTModelLoader.this) {
if(super.getPackage() == null){
super.setPackage(modules.getLanguageModule().getDirectPackage("ceylon.language"));
}
return super.getPackage();
}
}
/**
* Search for a declaration in the language module.
*/
public Declaration getLanguageModuleDeclaration(String name) {
synchronized (JDTModelLoader.this) {
if (languageModuledeclarations.containsKey(name)) {
return languageModuledeclarations.get(name);
}
languageModuledeclarations.put(name, null);
Declaration decl = super.getLanguageModuleDeclaration(name);
languageModuledeclarations.put(name, decl);
return decl;
}
}
};
this.typeParser = new TypeParser(this, typeFactory);
this.timer = new Timer(false);
createLookupEnvironment();
}
public void createLookupEnvironment() {
try {
lookupEnvironment = new LookupEnvironment(new ITypeRequestor() {
private Parser basicParser;
@Override
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding,
AccessRestriction accessRestriction) {
// case of SearchableEnvironment of an IJavaProject is used
ISourceType sourceType = sourceTypes[0];
while (sourceType.getEnclosingType() != null)
sourceType = sourceType.getEnclosingType();
if (sourceType instanceof SourceTypeElementInfo) {
// get source
SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType;
IType type = elementInfo.getHandle();
ICompilationUnit sourceUnit = (ICompilationUnit) type.getCompilationUnit();
accept(sourceUnit, accessRestriction);
} else {
CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, 0);
CompilationUnitDeclaration unit =
SourceTypeConverter.buildCompilationUnit(
sourceTypes,
SourceTypeConverter.FIELD_AND_METHOD // need field and methods
| SourceTypeConverter.MEMBER_TYPE, // need member types
// no need for field initialization
lookupEnvironment.problemReporter,
result);
lookupEnvironment.buildTypeBindings(unit, accessRestriction);
lookupEnvironment.completeTypeBindings(unit, true);
}
}
@Override
public void accept(IBinaryType binaryType, PackageBinding packageBinding,
AccessRestriction accessRestriction) {
lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);
}
@Override
public void accept(ICompilationUnit sourceUnit,
AccessRestriction accessRestriction) {
// Switch the current policy and compilation result for this unit to the requested one.
CompilationResult unitResult = new CompilationResult(sourceUnit, 1, 1, compilerOptions.maxProblemsPerUnit);
try {
CompilationUnitDeclaration parsedUnit = basicParser().dietParse(sourceUnit, unitResult);
lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
lookupEnvironment.completeTypeBindings(parsedUnit, true);
} catch (AbortCompilationUnit e) {
// at this point, currentCompilationUnitResult may not be sourceUnit, but some other
// one requested further along to resolve sourceUnit.
if (unitResult.compilationUnit == sourceUnit) { // only report once
//requestor.acceptResult(unitResult.tagAsAccepted());
} else {
throw e; // want to abort enclosing request to compile
}
}
// Display unit error in debug mode
if (BasicSearchEngine.VERBOSE) {
if (unitResult.problemCount > 0) {
System.out.println(unitResult);
}
}
}
private Parser basicParser() {
if (this.basicParser == null) {
ProblemReporter problemReporter =
new ProblemReporter(
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
compilerOptions,
new DefaultProblemFactory());
this.basicParser = new Parser(problemReporter, false);
this.basicParser.reportOnlyOneSyntaxError = true;
}
return this.basicParser;
}
}, compilerOptions, problemReporter, ((JavaProject)javaProject).newSearchableNameEnvironment((WorkingCopyOwner)null));
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TODO : remove when the bug in the AbstractModelLoader is corrected
@Override
public synchronized LazyPackage findOrCreatePackage(Module module, String pkgName) {
LazyPackage pkg = super.findOrCreatePackage(module, pkgName);
if ("".equals(pkgName)) {
pkg.setName(Collections.<String>emptyList());
}
if (pkg.getModule() != null
&& pkg.getModule().isJava()){
pkg.setShared(true);
}
Module currentModule = pkg.getModule();
if (currentModule.equals(modules.getDefaultModule()) && ! currentModule.equals(module)) {
currentModule.getPackages().remove(pkg);
pkg.setModule(null);
if (module != null) {
module.getPackages().add(pkg);
pkg.setModule(module);
}
}
return pkg;
}
@Override
public void loadStandardModules() {
// make sure the jdk modules are loaded
for(String jdkModule : JDKPackageList.getJDKModuleNames())
findOrCreateModule(jdkModule);
for(String jdkOracleModule : JDKPackageList.getOracleJDKModuleNames())
findOrCreateModule(jdkOracleModule);
/*
* We start by loading java.lang because we will need it no matter what.
*/
loadPackage("java.lang", false);
}
private String getQualifiedName(final String pkgName, String name) {
// FIXME: some refactoring needed
name = Util.quoteIfJavaKeyword(name);
String className = pkgName.isEmpty() ? name : Util.quoteJavaKeywords(pkgName) + "." + name;
return className;
}
@Override
public synchronized boolean loadPackage(String packageName, boolean loadDeclarations) {
packageName = Util.quoteJavaKeywords(packageName);
if(loadDeclarations && !loadedPackages.add(packageName)){
return true;
}
Module module = lookupModule(packageName);
if (module instanceof JDTModule) {
JDTModule jdtModule = (JDTModule) module;
List<IPackageFragmentRoot> roots = jdtModule.getPackageFragmentRoots();
IPackageFragment packageFragment = null;
for (IPackageFragmentRoot root : roots) {
// skip packages that are not present
if(!root.exists())
continue;
try {
IClasspathEntry entry = root.getRawClasspathEntry();
//TODO: is the following really necessary?
//Note that getContentKind() returns an undefined
//value for a classpath container or variable
if (entry.getEntryKind()!=IClasspathEntry.CPE_CONTAINER &&
entry.getEntryKind()!=IClasspathEntry.CPE_VARIABLE &&
entry.getContentKind()==IPackageFragmentRoot.K_SOURCE &&
!CeylonBuilder.isCeylonSourceEntry(entry)) {
continue;
}
packageFragment = root.getPackageFragment(packageName);
if(packageFragment.exists()){
if(!loadDeclarations) {
// we found the package
return true;
}else{
try {
for (IClassFile classFile : packageFragment.getClassFiles()) {
// skip removed class files
if(!classFile.exists())
continue;
IType type = classFile.getType();
if (type.exists() && ! type.isMember() && !sourceDeclarations.containsKey(getQualifiedName(type.getPackageFragment().getElementName(), type.getTypeQualifiedName()))) {
convertToDeclaration(type.getFullyQualifiedName(), DeclarationType.VALUE);
}
}
for (org.eclipse.jdt.core.ICompilationUnit compilationUnit : packageFragment.getCompilationUnits()) {
// skip removed CUs
if(!compilationUnit.exists())
continue;
for (IType type : compilationUnit.getTypes()) {
if (type.exists() && ! type.isMember() && !sourceDeclarations.containsKey(getQualifiedName(type.getPackageFragment().getElementName(), type.getTypeQualifiedName()))) {
convertToDeclaration(type.getFullyQualifiedName(), DeclarationType.VALUE);
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
return false;
}
private Module lookupModule(String packageName) {
Module module = lookupModuleInternal(packageName);
if (module != null) {
return module;
}
return modules.getDefaultModule();
}
@Override
protected Module lookupModuleInternal(String packageName) {
for(Module module : modules.getListOfModules()){
if(module instanceof LazyModule){
if(((LazyModule)module).containsPackage(packageName))
return module;
}else if(isSubPackage(module.getNameAsString(), packageName))
return module;
}
return null;
}
private boolean isSubPackage(String moduleName, String pkgName) {
return pkgName.equals(moduleName)
|| pkgName.startsWith(moduleName+".");
}
synchronized private LookupEnvironment getLookupEnvironment() {
if (mustResetLookupEnvironment) {
lookupEnvironment.reset();
mustResetLookupEnvironment = false;
}
return lookupEnvironment;
}
@Override
public synchronized ClassMirror lookupNewClassMirror(String name) {
if (sourceDeclarations.containsKey(name)) {
return new SourceClass(sourceDeclarations.get(name));
}
return buildClassMirror(name);
}
private ClassMirror buildClassMirror(String name) {
try {
IType type = javaProject.findType(name);
if (type == null) {
return null;
}
LookupEnvironment theLookupEnvironment = getLookupEnvironment();
if (type.isBinary()) {
ClassFile classFile = (ClassFile) type.getClassFile();
if (classFile != null) {
IPackageFragmentRoot fragmentRoot = classFile.getPackageFragmentRoot();
if (fragmentRoot != null) {
if (isInCeylonClassesOutputFolder(fragmentRoot.getPath())) {
return null;
}
}
IFile classFileRsrc = (IFile) classFile.getCorrespondingResource();
IBinaryType binaryType = classFile.getBinaryTypeInfo(classFileRsrc, true);
if (classFileRsrc!=null && !classFileRsrc.exists()) {
//the .class file has been deleted
return null;
}
BinaryTypeBinding binaryTypeBinding = theLookupEnvironment.cacheBinaryType(binaryType, null);
if (binaryTypeBinding == null) {
char[][] compoundName = CharOperation.splitOn('/', binaryType.getName());
ReferenceBinding existingType = theLookupEnvironment.getCachedType(compoundName);
if (existingType == null || ! (existingType instanceof BinaryTypeBinding)) {
return null;
}
binaryTypeBinding = (BinaryTypeBinding) existingType;
}
return new JDTClass(binaryTypeBinding, theLookupEnvironment);
}
} else {
char[][] compoundName = CharOperation.splitOn('.', type.getFullyQualifiedName().toCharArray());
ReferenceBinding referenceBinding = theLookupEnvironment.getType(compoundName);
if (referenceBinding != null) {
if (referenceBinding instanceof ProblemReferenceBinding) {
ProblemReferenceBinding problemReferenceBinding = (ProblemReferenceBinding) referenceBinding;
if (problemReferenceBinding.problemId() == ProblemReasons.InternalNameProvided) {
referenceBinding = problemReferenceBinding.closestReferenceMatch();
} else {
System.out.println(ProblemReferenceBinding.problemReasonString(problemReferenceBinding.problemId()));
return null;
}
}
return new JDTClass(referenceBinding, theLookupEnvironment);
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
return null;
}
@Override
public synchronized Declaration convertToDeclaration(String typeName,
DeclarationType declarationType) {
if (sourceDeclarations.containsKey(typeName)) {
return sourceDeclarations.get(typeName).getModelDeclaration();
}
try {
return super.convertToDeclaration(typeName, declarationType);
} catch(RuntimeException e) {
return null;
}
}
@Override
public void addModuleToClassPath(Module module, ArtifactResult artifact) {}
@Override
protected boolean isOverridingMethod(MethodMirror methodSymbol) {
return ((JDTMethod)methodSymbol).isOverridingMethod();
}
@Override
protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) {
Unit unit = null;
JDTClass jdtClass = (JDTClass)classMirror;
String unitName = jdtClass.getFileName();
if (!jdtClass.isBinary()) {
for (Unit unitToTest : pkg.getUnits()) {
if (unitToTest.getFilename().equals(unitName)) {
return unitToTest;
}
}
}
unit = new ExternalUnit();
unit.setFilename(jdtClass.getFileName());
unit.setPackage(pkg);
return unit;
}
@Override
protected void logError(String message) {
//System.err.println("ERROR: "+message);
}
@Override
protected void logWarning(String message) {
//System.err.println("WARNING: "+message);
}
@Override
protected void logVerbose(String message) {
//System.err.println("NOTE: "+message);
}
@Override
public synchronized void removeDeclarations(List<Declaration> declarations) {
List<Declaration> allDeclarations = new ArrayList<Declaration>(declarations.size());
allDeclarations.addAll(declarations);
for (Declaration declaration : declarations) {
retrieveInnerDeclarations(declaration, allDeclarations);
}
for (Declaration decl : allDeclarations) {
String fqn = getQualifiedName(decl.getContainer().getQualifiedNameString(), decl.getName());
sourceDeclarations.remove(fqn);
}
super.removeDeclarations(allDeclarations);
mustResetLookupEnvironment = true;
}
private void retrieveInnerDeclarations(Declaration declaration,
List<Declaration> allDeclarations) {
List<Declaration> members = declaration.getMembers();
allDeclarations.addAll(members);
for (Declaration member : members) {
retrieveInnerDeclarations(member, allDeclarations);
}
}
private final Map<String, CeylonDeclaration> sourceDeclarations = new TreeMap<String, CeylonDeclaration>();
public synchronized Set<String> getSourceDeclarations() {
Set<String> declarations = new HashSet<String>();
declarations.addAll(sourceDeclarations.keySet());
return declarations;
}
public static interface SourceFileObjectManager {
void setupSourceFileObjects(List<?> treeHolders);
}
private SourceFileObjectManager additionalSourceFileObjectsManager = null;
public synchronized void setSourceFileObjectManager(SourceFileObjectManager manager) {
additionalSourceFileObjectsManager = manager;
}
public synchronized void setupSourceFileObjects(List<?> treeHolders) {
addSourcePhasedUnits(treeHolders, true);
if (additionalSourceFileObjectsManager != null) {
additionalSourceFileObjectsManager.setupSourceFileObjects(treeHolders);
}
}
public synchronized void addSourcePhasedUnits(List<?> treeHolders, final boolean isSourceToCompile) {
for (Object treeHolder : treeHolders) {
if (treeHolder instanceof PhasedUnit) {
final PhasedUnit unit = (PhasedUnit) treeHolder;
final String pkgName = unit.getPackage().getQualifiedNameString();
unit.getCompilationUnit().visit(new SourceDeclarationVisitor(){
@Override
public void loadFromSource(Tree.Declaration decl) {
if (decl.getIdentifier()!=null) {
String name = Util.quoteIfJavaKeyword(decl.getIdentifier().getText());
String fqn = getQualifiedName(pkgName, name);
if (! sourceDeclarations.containsKey(fqn)) {
sourceDeclarations.put(fqn, new CeylonDeclaration(unit, decl, isSourceToCompile));
}
}
}
});
}
}
}
public void addSourceArchivePhasedUnits(List<PhasedUnit> sourceArchivePhasedUnits) {
addSourcePhasedUnits(sourceArchivePhasedUnits, false);
}
public synchronized void clearCachesOnPackage(String packageName) {
List<String> keysToRemove = new ArrayList<String>(classMirrorCache.size());
for (Entry<String, ClassMirror> element : classMirrorCache.entrySet()) {
if (element.getValue() == null) {
String className = element.getKey();
if (className != null) {
String classPackageName =className.replaceAll("\\.[^\\.]+$", "");
if (classPackageName.equals(packageName)) {
keysToRemove.add(className);
}
}
}
}
for (String keyToRemove : keysToRemove) {
classMirrorCache.remove(keyToRemove);
}
loadedPackages.remove(packageName);
}
@Override
protected LazyValue makeToplevelAttribute(ClassMirror classMirror) {
if (classMirror instanceof SourceClass) {
return (LazyValue) (((SourceClass) classMirror).getModelDeclaration());
}
return super.makeToplevelAttribute(classMirror);
}
@Override
protected LazyMethod makeToplevelMethod(ClassMirror classMirror) {
if (classMirror instanceof SourceClass) {
return (LazyMethod) (((SourceClass) classMirror).getModelDeclaration());
}
return super.makeToplevelMethod(classMirror);
}
@Override
protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass,
MethodMirror constructor, boolean forTopLevelObject) {
if (classMirror instanceof SourceClass) {
return (LazyClass) (((SourceClass) classMirror).getModelDeclaration());
}
return super.makeLazyClass(classMirror, superClass, constructor,
forTopLevelObject);
}
@Override
protected LazyInterface makeLazyInterface(ClassMirror classMirror) {
if (classMirror instanceof SourceClass) {
return (LazyInterface) ((SourceClass) classMirror).getModelDeclaration();
}
return super.makeLazyInterface(classMirror);
}
public TypeFactory getTypeFactory() {
return (TypeFactory) typeFactory;
}
public synchronized void reset() {
internalCreate();
declarationsByName.clear();
unitsByPackage.clear();
loadedPackages.clear();
packageDescriptorsNeedLoading = false;
classMirrorCache.clear();
}
public synchronized void completeFromClasses() {
for (Entry<String, CeylonDeclaration> entry : sourceDeclarations.entrySet()) {
CeylonDeclaration declaration = entry.getValue();
if (mustCompleteFromClasses(declaration)) {
ClassMirror classMirror = buildClassMirror(entry.getKey());
if (classMirror == null) {
continue;
}
final Declaration binaryDeclaration = getOrCreateDeclaration(classMirror,
DeclarationType.TYPE,
new ArrayList<Declaration>(), new boolean[1]);
if (binaryDeclaration == null) {
continue;
}
declaration.getAstDeclaration().visit(new Visitor() {
@Override
public void visit(Tree.AnyAttribute that) {
super.visit(that);
Declaration binaryMember = binaryDeclaration.getMember(that.getDeclarationModel().getName(), Collections.<ProducedType>emptyList(), false);
if (binaryMember != null) {
ProducedType type = ((TypedDeclaration)binaryMember).getType();
if(type == null)
return;
String underlyingType = type.getUnderlyingType();
if (underlyingType != null) {
ProducedType typeToComplete = that.getDeclarationModel().getType();
if (typeToComplete != null) {
typeToComplete.setUnderlyingType(underlyingType);
}
}
}
}
@Override
public void visit(Tree.AttributeSetterDefinition that) {
super.visit(that);
Declaration binaryMember = binaryDeclaration.getMember(that.getDeclarationModel().getName(), Collections.<ProducedType>emptyList(), false);
if (binaryMember != null) {
String underlyingType = ((TypedDeclaration)binaryMember).getType().getUnderlyingType();
if (underlyingType != null) {
ProducedType typeToComplete = that.getDeclarationModel().getType();
if (typeToComplete != null) {
typeToComplete.setUnderlyingType(underlyingType);
}
}
}
}
@Override
public void visit(Tree.AnyMethod that) {
super.visit(that);
Method method = that.getDeclarationModel();
Method binaryMethod = (Method) binaryDeclaration.getMember(method.getName(), Collections.<ProducedType>emptyList(), false);
if (binaryMethod != null) {
String underlyingType = ((TypedDeclaration)binaryMethod).getType().getUnderlyingType();
if (underlyingType != null) {
ProducedType typeToComplete = that.getDeclarationModel().getType();
if (typeToComplete != null) {
typeToComplete.setUnderlyingType(underlyingType);
}
}
Iterator<ParameterList> binaryParamLists = binaryMethod.getParameterLists().iterator();
for (ParameterList paramList : method.getParameterLists()) {
if (binaryParamLists.hasNext()) {
ParameterList binaryParamList = binaryParamLists.next();
Iterator<Parameter> binaryParams = binaryParamList.getParameters().iterator();
for (Parameter param : paramList.getParameters()) {
if (binaryParams.hasNext()) {
Parameter binaryParam = binaryParams.next();
String paramUnderlyingType = binaryParam.getType().getUnderlyingType();
if (paramUnderlyingType != null) {
ProducedType typeToComplete = param.getType();
if (typeToComplete != null) {
typeToComplete.setUnderlyingType(paramUnderlyingType);
}
}
}
}
}
}
}
}
});
}
}
}
private boolean mustCompleteFromClasses(CeylonDeclaration d) {
return !d.isSourceToCompile() && d.getPhasedUnit().getUnit().getPackage().getQualifiedNameString().startsWith("ceylon.language");
}
}
| plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/model/loader/JDTModelLoader.java | /*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.eclipse.core.model.loader;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.isInCeylonClassesOutputFolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.WorkingCopyOwner;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.ISourceType;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
import org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons;
import org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.core.ClassFile;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jdt.internal.core.SourceTypeElementInfo;
import org.eclipse.jdt.internal.core.search.BasicSearchEngine;
import com.redhat.ceylon.cmr.api.ArtifactResult;
import com.redhat.ceylon.compiler.java.loader.TypeFactory;
import com.redhat.ceylon.compiler.java.util.Timer;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.loader.AbstractModelLoader;
import com.redhat.ceylon.compiler.loader.JDKPackageList;
import com.redhat.ceylon.compiler.loader.SourceDeclarationVisitor;
import com.redhat.ceylon.compiler.loader.TypeParser;
import com.redhat.ceylon.compiler.loader.mirror.ClassMirror;
import com.redhat.ceylon.compiler.loader.mirror.MethodMirror;
import com.redhat.ceylon.compiler.loader.model.LazyClass;
import com.redhat.ceylon.compiler.loader.model.LazyInterface;
import com.redhat.ceylon.compiler.loader.model.LazyMethod;
import com.redhat.ceylon.compiler.loader.model.LazyModule;
import com.redhat.ceylon.compiler.loader.model.LazyPackage;
import com.redhat.ceylon.compiler.loader.model.LazyValue;
import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.ExternalUnit;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Modules;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.core.model.CeylonDeclaration;
/**
* A model loader which uses the JDT model.
*
* @author David Festal <[email protected]>
*/
public class JDTModelLoader extends AbstractModelLoader {
private IJavaProject javaProject;
private CompilerOptions compilerOptions;
private ProblemReporter problemReporter;
private LookupEnvironment lookupEnvironment;
private boolean mustResetLookupEnvironment = false;
private Map<String, Declaration> languageModuledeclarations;
public JDTModelLoader(final ModuleManager moduleManager, final Modules modules){
this.moduleManager = moduleManager;
this.modules = modules;
javaProject = ((JDTModuleManager)moduleManager).getJavaProject();
compilerOptions = new CompilerOptions(javaProject.getOptions(true));
compilerOptions.ignoreMethodBodies = true;
compilerOptions.storeAnnotations = true;
problemReporter = new ProblemReporter(
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
compilerOptions,
new DefaultProblemFactory());
internalCreate();
}
private void internalCreate() {
this.languageModuledeclarations = new HashMap<String, Declaration>();
this.typeFactory = new TypeFactory(moduleManager.getContext()) {
@Override
public Package getPackage() {
synchronized (JDTModelLoader.this) {
if(super.getPackage() == null){
super.setPackage(modules.getLanguageModule().getDirectPackage("ceylon.language"));
}
return super.getPackage();
}
}
/**
* Search for a declaration in the language module.
*/
public Declaration getLanguageModuleDeclaration(String name) {
synchronized (JDTModelLoader.this) {
if (languageModuledeclarations.containsKey(name)) {
return languageModuledeclarations.get(name);
}
languageModuledeclarations.put(name, null);
Declaration decl = super.getLanguageModuleDeclaration(name);
languageModuledeclarations.put(name, decl);
return decl;
}
}
};
this.typeParser = new TypeParser(this, typeFactory);
createLookupEnvironment();
}
public void createLookupEnvironment() {
try {
lookupEnvironment = new LookupEnvironment(new ITypeRequestor() {
private Parser basicParser;
@Override
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding,
AccessRestriction accessRestriction) {
// case of SearchableEnvironment of an IJavaProject is used
ISourceType sourceType = sourceTypes[0];
while (sourceType.getEnclosingType() != null)
sourceType = sourceType.getEnclosingType();
if (sourceType instanceof SourceTypeElementInfo) {
// get source
SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) sourceType;
IType type = elementInfo.getHandle();
ICompilationUnit sourceUnit = (ICompilationUnit) type.getCompilationUnit();
accept(sourceUnit, accessRestriction);
} else {
CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, 0);
CompilationUnitDeclaration unit =
SourceTypeConverter.buildCompilationUnit(
sourceTypes,
SourceTypeConverter.FIELD_AND_METHOD // need field and methods
| SourceTypeConverter.MEMBER_TYPE, // need member types
// no need for field initialization
lookupEnvironment.problemReporter,
result);
lookupEnvironment.buildTypeBindings(unit, accessRestriction);
lookupEnvironment.completeTypeBindings(unit, true);
}
}
@Override
public void accept(IBinaryType binaryType, PackageBinding packageBinding,
AccessRestriction accessRestriction) {
lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);
}
@Override
public void accept(ICompilationUnit sourceUnit,
AccessRestriction accessRestriction) {
// Switch the current policy and compilation result for this unit to the requested one.
CompilationResult unitResult = new CompilationResult(sourceUnit, 1, 1, compilerOptions.maxProblemsPerUnit);
try {
CompilationUnitDeclaration parsedUnit = basicParser().dietParse(sourceUnit, unitResult);
lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
lookupEnvironment.completeTypeBindings(parsedUnit, true);
} catch (AbortCompilationUnit e) {
// at this point, currentCompilationUnitResult may not be sourceUnit, but some other
// one requested further along to resolve sourceUnit.
if (unitResult.compilationUnit == sourceUnit) { // only report once
//requestor.acceptResult(unitResult.tagAsAccepted());
} else {
throw e; // want to abort enclosing request to compile
}
}
// Display unit error in debug mode
if (BasicSearchEngine.VERBOSE) {
if (unitResult.problemCount > 0) {
System.out.println(unitResult);
}
}
}
private Parser basicParser() {
if (this.basicParser == null) {
ProblemReporter problemReporter =
new ProblemReporter(
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
compilerOptions,
new DefaultProblemFactory());
this.basicParser = new Parser(problemReporter, false);
this.basicParser.reportOnlyOneSyntaxError = true;
}
return this.basicParser;
}
}, compilerOptions, problemReporter, ((JavaProject)javaProject).newSearchableNameEnvironment((WorkingCopyOwner)null));
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TODO : remove when the bug in the AbstractModelLoader is corrected
@Override
public synchronized LazyPackage findOrCreatePackage(Module module, String pkgName) {
LazyPackage pkg = super.findOrCreatePackage(module, pkgName);
if ("".equals(pkgName)) {
pkg.setName(Collections.<String>emptyList());
}
if (pkg.getModule() != null
&& pkg.getModule().isJava()){
pkg.setShared(true);
}
Module currentModule = pkg.getModule();
if (currentModule.equals(modules.getDefaultModule()) && ! currentModule.equals(module)) {
currentModule.getPackages().remove(pkg);
pkg.setModule(null);
if (module != null) {
module.getPackages().add(pkg);
pkg.setModule(module);
}
}
return pkg;
}
@Override
public void loadStandardModules() {
// make sure the jdk modules are loaded
for(String jdkModule : JDKPackageList.getJDKModuleNames())
findOrCreateModule(jdkModule);
for(String jdkOracleModule : JDKPackageList.getOracleJDKModuleNames())
findOrCreateModule(jdkOracleModule);
/*
* We start by loading java.lang because we will need it no matter what.
*/
loadPackage("java.lang", false);
}
private String getQualifiedName(final String pkgName, String name) {
// FIXME: some refactoring needed
name = Util.quoteIfJavaKeyword(name);
String className = pkgName.isEmpty() ? name : Util.quoteJavaKeywords(pkgName) + "." + name;
return className;
}
@Override
public synchronized boolean loadPackage(String packageName, boolean loadDeclarations) {
packageName = Util.quoteJavaKeywords(packageName);
if(loadDeclarations && !loadedPackages.add(packageName)){
return true;
}
Module module = lookupModule(packageName);
if (module instanceof JDTModule) {
JDTModule jdtModule = (JDTModule) module;
List<IPackageFragmentRoot> roots = jdtModule.getPackageFragmentRoots();
IPackageFragment packageFragment = null;
for (IPackageFragmentRoot root : roots) {
// skip packages that are not present
if(!root.exists())
continue;
try {
IClasspathEntry entry = root.getRawClasspathEntry();
//TODO: is the following really necessary?
//Note that getContentKind() returns an undefined
//value for a classpath container or variable
if (entry.getEntryKind()!=IClasspathEntry.CPE_CONTAINER &&
entry.getEntryKind()!=IClasspathEntry.CPE_VARIABLE &&
entry.getContentKind()==IPackageFragmentRoot.K_SOURCE &&
!CeylonBuilder.isCeylonSourceEntry(entry)) {
continue;
}
packageFragment = root.getPackageFragment(packageName);
if(packageFragment.exists()){
if(!loadDeclarations) {
// we found the package
return true;
}else{
try {
for (IClassFile classFile : packageFragment.getClassFiles()) {
// skip removed class files
if(!classFile.exists())
continue;
IType type = classFile.getType();
if (type.exists() && ! type.isMember() && !sourceDeclarations.containsKey(getQualifiedName(type.getPackageFragment().getElementName(), type.getTypeQualifiedName()))) {
convertToDeclaration(type.getFullyQualifiedName(), DeclarationType.VALUE);
}
}
for (org.eclipse.jdt.core.ICompilationUnit compilationUnit : packageFragment.getCompilationUnits()) {
// skip removed CUs
if(!compilationUnit.exists())
continue;
for (IType type : compilationUnit.getTypes()) {
if (type.exists() && ! type.isMember() && !sourceDeclarations.containsKey(getQualifiedName(type.getPackageFragment().getElementName(), type.getTypeQualifiedName()))) {
convertToDeclaration(type.getFullyQualifiedName(), DeclarationType.VALUE);
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
}
return false;
}
private Module lookupModule(String packageName) {
Module module = lookupModuleInternal(packageName);
if (module != null) {
return module;
}
return modules.getDefaultModule();
}
@Override
protected Module lookupModuleInternal(String packageName) {
for(Module module : modules.getListOfModules()){
if(module instanceof LazyModule){
if(((LazyModule)module).containsPackage(packageName))
return module;
}else if(isSubPackage(module.getNameAsString(), packageName))
return module;
}
return null;
}
private boolean isSubPackage(String moduleName, String pkgName) {
return pkgName.equals(moduleName)
|| pkgName.startsWith(moduleName+".");
}
synchronized private LookupEnvironment getLookupEnvironment() {
if (mustResetLookupEnvironment) {
lookupEnvironment.reset();
mustResetLookupEnvironment = false;
}
return lookupEnvironment;
}
@Override
public synchronized ClassMirror lookupNewClassMirror(String name) {
if (sourceDeclarations.containsKey(name)) {
return new SourceClass(sourceDeclarations.get(name));
}
return buildClassMirror(name);
}
private ClassMirror buildClassMirror(String name) {
try {
IType type = javaProject.findType(name);
if (type == null) {
return null;
}
LookupEnvironment theLookupEnvironment = getLookupEnvironment();
if (type.isBinary()) {
ClassFile classFile = (ClassFile) type.getClassFile();
if (classFile != null) {
IPackageFragmentRoot fragmentRoot = classFile.getPackageFragmentRoot();
if (fragmentRoot != null) {
if (isInCeylonClassesOutputFolder(fragmentRoot.getPath())) {
return null;
}
}
IFile classFileRsrc = (IFile) classFile.getCorrespondingResource();
IBinaryType binaryType = classFile.getBinaryTypeInfo(classFileRsrc, true);
if (classFileRsrc!=null && !classFileRsrc.exists()) {
//the .class file has been deleted
return null;
}
BinaryTypeBinding binaryTypeBinding = theLookupEnvironment.cacheBinaryType(binaryType, null);
if (binaryTypeBinding == null) {
char[][] compoundName = CharOperation.splitOn('/', binaryType.getName());
ReferenceBinding existingType = theLookupEnvironment.getCachedType(compoundName);
if (existingType == null || ! (existingType instanceof BinaryTypeBinding)) {
return null;
}
binaryTypeBinding = (BinaryTypeBinding) existingType;
}
return new JDTClass(binaryTypeBinding, theLookupEnvironment);
}
} else {
char[][] compoundName = CharOperation.splitOn('.', type.getFullyQualifiedName().toCharArray());
ReferenceBinding referenceBinding = theLookupEnvironment.getType(compoundName);
if (referenceBinding != null) {
if (referenceBinding instanceof ProblemReferenceBinding) {
ProblemReferenceBinding problemReferenceBinding = (ProblemReferenceBinding) referenceBinding;
if (problemReferenceBinding.problemId() == ProblemReasons.InternalNameProvided) {
referenceBinding = problemReferenceBinding.closestReferenceMatch();
} else {
System.out.println(ProblemReferenceBinding.problemReasonString(problemReferenceBinding.problemId()));
return null;
}
}
return new JDTClass(referenceBinding, theLookupEnvironment);
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
return null;
}
@Override
public synchronized Declaration convertToDeclaration(String typeName,
DeclarationType declarationType) {
if (sourceDeclarations.containsKey(typeName)) {
return sourceDeclarations.get(typeName).getModelDeclaration();
}
try {
return super.convertToDeclaration(typeName, declarationType);
} catch(RuntimeException e) {
return null;
}
}
@Override
public void addModuleToClassPath(Module module, ArtifactResult artifact) {}
@Override
protected boolean isOverridingMethod(MethodMirror methodSymbol) {
return ((JDTMethod)methodSymbol).isOverridingMethod();
}
@Override
protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) {
Unit unit = null;
JDTClass jdtClass = (JDTClass)classMirror;
String unitName = jdtClass.getFileName();
if (!jdtClass.isBinary()) {
for (Unit unitToTest : pkg.getUnits()) {
if (unitToTest.getFilename().equals(unitName)) {
return unitToTest;
}
}
}
unit = new ExternalUnit();
unit.setFilename(jdtClass.getFileName());
unit.setPackage(pkg);
return unit;
}
@Override
protected void logError(String message) {
//System.err.println("ERROR: "+message);
}
@Override
protected void logWarning(String message) {
//System.err.println("WARNING: "+message);
}
@Override
protected void logVerbose(String message) {
//System.err.println("NOTE: "+message);
}
@Override
public synchronized void removeDeclarations(List<Declaration> declarations) {
List<Declaration> allDeclarations = new ArrayList<Declaration>(declarations.size());
allDeclarations.addAll(declarations);
for (Declaration declaration : declarations) {
retrieveInnerDeclarations(declaration, allDeclarations);
}
for (Declaration decl : allDeclarations) {
String fqn = getQualifiedName(decl.getContainer().getQualifiedNameString(), decl.getName());
sourceDeclarations.remove(fqn);
}
super.removeDeclarations(allDeclarations);
mustResetLookupEnvironment = true;
}
private void retrieveInnerDeclarations(Declaration declaration,
List<Declaration> allDeclarations) {
List<Declaration> members = declaration.getMembers();
allDeclarations.addAll(members);
for (Declaration member : members) {
retrieveInnerDeclarations(member, allDeclarations);
}
}
private final Map<String, CeylonDeclaration> sourceDeclarations = new TreeMap<String, CeylonDeclaration>();
public synchronized Set<String> getSourceDeclarations() {
Set<String> declarations = new HashSet<String>();
declarations.addAll(sourceDeclarations.keySet());
return declarations;
}
public static interface SourceFileObjectManager {
void setupSourceFileObjects(List<?> treeHolders);
}
private SourceFileObjectManager additionalSourceFileObjectsManager = null;
public synchronized void setSourceFileObjectManager(SourceFileObjectManager manager) {
additionalSourceFileObjectsManager = manager;
}
public synchronized void setupSourceFileObjects(List<?> treeHolders) {
addSourcePhasedUnits(treeHolders, true);
if (additionalSourceFileObjectsManager != null) {
additionalSourceFileObjectsManager.setupSourceFileObjects(treeHolders);
}
}
public synchronized void addSourcePhasedUnits(List<?> treeHolders, final boolean isSourceToCompile) {
for (Object treeHolder : treeHolders) {
if (treeHolder instanceof PhasedUnit) {
final PhasedUnit unit = (PhasedUnit) treeHolder;
final String pkgName = unit.getPackage().getQualifiedNameString();
unit.getCompilationUnit().visit(new SourceDeclarationVisitor(){
@Override
public void loadFromSource(Tree.Declaration decl) {
if (decl.getIdentifier()!=null) {
String name = Util.quoteIfJavaKeyword(decl.getIdentifier().getText());
String fqn = getQualifiedName(pkgName, name);
if (! sourceDeclarations.containsKey(fqn)) {
sourceDeclarations.put(fqn, new CeylonDeclaration(unit, decl, isSourceToCompile));
}
}
}
});
}
}
}
public void addSourceArchivePhasedUnits(List<PhasedUnit> sourceArchivePhasedUnits) {
addSourcePhasedUnits(sourceArchivePhasedUnits, false);
}
public synchronized void clearCachesOnPackage(String packageName) {
List<String> keysToRemove = new ArrayList<String>(classMirrorCache.size());
for (Entry<String, ClassMirror> element : classMirrorCache.entrySet()) {
if (element.getValue() == null) {
String className = element.getKey();
if (className != null) {
String classPackageName =className.replaceAll("\\.[^\\.]+$", "");
if (classPackageName.equals(packageName)) {
keysToRemove.add(className);
}
}
}
}
for (String keyToRemove : keysToRemove) {
classMirrorCache.remove(keyToRemove);
}
loadedPackages.remove(packageName);
}
@Override
protected LazyValue makeToplevelAttribute(ClassMirror classMirror) {
if (classMirror instanceof SourceClass) {
return (LazyValue) (((SourceClass) classMirror).getModelDeclaration());
}
return super.makeToplevelAttribute(classMirror);
}
@Override
protected LazyMethod makeToplevelMethod(ClassMirror classMirror) {
if (classMirror instanceof SourceClass) {
return (LazyMethod) (((SourceClass) classMirror).getModelDeclaration());
}
return super.makeToplevelMethod(classMirror);
}
@Override
protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass,
MethodMirror constructor, boolean forTopLevelObject) {
if (classMirror instanceof SourceClass) {
return (LazyClass) (((SourceClass) classMirror).getModelDeclaration());
}
return super.makeLazyClass(classMirror, superClass, constructor,
forTopLevelObject);
}
@Override
protected LazyInterface makeLazyInterface(ClassMirror classMirror) {
if (classMirror instanceof SourceClass) {
return (LazyInterface) ((SourceClass) classMirror).getModelDeclaration();
}
return super.makeLazyInterface(classMirror);
}
public TypeFactory getTypeFactory() {
return (TypeFactory) typeFactory;
}
public synchronized void reset() {
internalCreate();
declarationsByName.clear();
unitsByPackage.clear();
loadedPackages.clear();
packageDescriptorsNeedLoading = false;
classMirrorCache.clear();
}
public synchronized void completeFromClasses() {
for (Entry<String, CeylonDeclaration> entry : sourceDeclarations.entrySet()) {
CeylonDeclaration declaration = entry.getValue();
if (mustCompleteFromClasses(declaration)) {
ClassMirror classMirror = buildClassMirror(entry.getKey());
if (classMirror == null) {
continue;
}
final Declaration binaryDeclaration = getOrCreateDeclaration(classMirror,
DeclarationType.TYPE,
new ArrayList<Declaration>(), new boolean[1]);
if (binaryDeclaration == null) {
continue;
}
declaration.getAstDeclaration().visit(new Visitor() {
@Override
public void visit(Tree.AnyAttribute that) {
super.visit(that);
Declaration binaryMember = binaryDeclaration.getMember(that.getDeclarationModel().getName(), Collections.<ProducedType>emptyList(), false);
if (binaryMember != null) {
ProducedType type = ((TypedDeclaration)binaryMember).getType();
if(type == null)
return;
String underlyingType = type.getUnderlyingType();
if (underlyingType != null) {
ProducedType typeToComplete = that.getDeclarationModel().getType();
if (typeToComplete != null) {
typeToComplete.setUnderlyingType(underlyingType);
}
}
}
}
@Override
public void visit(Tree.AttributeSetterDefinition that) {
super.visit(that);
Declaration binaryMember = binaryDeclaration.getMember(that.getDeclarationModel().getName(), Collections.<ProducedType>emptyList(), false);
if (binaryMember != null) {
String underlyingType = ((TypedDeclaration)binaryMember).getType().getUnderlyingType();
if (underlyingType != null) {
ProducedType typeToComplete = that.getDeclarationModel().getType();
if (typeToComplete != null) {
typeToComplete.setUnderlyingType(underlyingType);
}
}
}
}
@Override
public void visit(Tree.AnyMethod that) {
super.visit(that);
Method method = that.getDeclarationModel();
Method binaryMethod = (Method) binaryDeclaration.getMember(method.getName(), Collections.<ProducedType>emptyList(), false);
if (binaryMethod != null) {
String underlyingType = ((TypedDeclaration)binaryMethod).getType().getUnderlyingType();
if (underlyingType != null) {
ProducedType typeToComplete = that.getDeclarationModel().getType();
if (typeToComplete != null) {
typeToComplete.setUnderlyingType(underlyingType);
}
}
Iterator<ParameterList> binaryParamLists = binaryMethod.getParameterLists().iterator();
for (ParameterList paramList : method.getParameterLists()) {
if (binaryParamLists.hasNext()) {
ParameterList binaryParamList = binaryParamLists.next();
Iterator<Parameter> binaryParams = binaryParamList.getParameters().iterator();
for (Parameter param : paramList.getParameters()) {
if (binaryParams.hasNext()) {
Parameter binaryParam = binaryParams.next();
String paramUnderlyingType = binaryParam.getType().getUnderlyingType();
if (paramUnderlyingType != null) {
ProducedType typeToComplete = param.getType();
if (typeToComplete != null) {
typeToComplete.setUnderlyingType(paramUnderlyingType);
}
}
}
}
}
}
}
}
});
}
}
}
private boolean mustCompleteFromClasses(CeylonDeclaration d) {
return !d.isSourceToCompile() && d.getPhasedUnit().getUnit().getPackage().getQualifiedNameString().startsWith("ceylon.language");
}
}
| JDTModelLoader: don't forget to set the timer
| plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/model/loader/JDTModelLoader.java | JDTModelLoader: don't forget to set the timer | <ide><path>lugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/model/loader/JDTModelLoader.java
<ide> }
<ide> };
<ide> this.typeParser = new TypeParser(this, typeFactory);
<add> this.timer = new Timer(false);
<ide> createLookupEnvironment();
<ide> }
<ide> |
|
Java | bsd-3-clause | 6813b0260ca4007cbab6e9a131bdd28fbaa74bcb | 0 | piyushsh/choco3,Tiger66639/choco3,piyushsh/choco3,chocoteam/choco3,chocoteam/choco3,chocoteam/choco3,Tiger66639/choco3,Tiger66639/choco3,chocoteam/choco3,cp-profiler/choco3,PhilAndrew/choco3gwt,cp-profiler/choco3,PhilAndrew/choco3gwt,Tiger66639/choco3,piyushsh/choco3,cp-profiler/choco3,cp-profiler/choco3,piyushsh/choco3,PhilAndrew/choco3gwt | /**
* Copyright (c) 1999-2011, Ecole des Mines de Nantes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Ecole des Mines de Nantes nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package solver.variables.domain;
import choco.kernel.common.util.iterators.DisposableIntIterator;
import choco.kernel.memory.IEnvironment;
import choco.kernel.memory.IStateInt;
import solver.variables.domain.delta.Delta;
import solver.variables.domain.delta.IntDelta;
import solver.variables.domain.delta.NoDelta;
/**
* <br/>
*
* @author Charles Prud'homme
* @since 28 juil. 2010
*/
public final class IntervalIntDomain implements IIntDomain {
/**
* The backtrackable minimal value of the variable.
*/
private final choco.kernel.memory.IStateInt lowerbound;
/**
* The backtrackable maximal value of the variable.
*/
private final IStateInt upperbound;
private final choco.kernel.memory.IStateInt size;
protected DisposableIntIterator _cachedIterator;
IntDelta delta = NoDelta.singleton;
public IntervalIntDomain(int a, int b, IEnvironment environment) {
lowerbound = environment.makeInt(a);
upperbound = environment.makeInt(b);
size = environment.makeInt(b - a + 1);
// delta = new Delta();
}
/**
* {@inheritDoc}
*/
@Override
public boolean remove(int aValue) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAndUpdateDelta(int aValue) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean restrictAndUpdateDelta(int aValue) {
int ub = this.upperbound.get();
int i = this.lowerbound.get();
for (; i < aValue; i++) {
delta.add(i);
}
i = aValue+1;
for (; i <= ub; i++) {
delta.add(i);
}
this.lowerbound.set(aValue);
this.upperbound.set(aValue);
boolean change = size.get() > 1;
this.size.set(1);
return change;
}
/**
* {@inheritDoc}
*/
@Override
public boolean restrict(int aValue) {
this.lowerbound.set(aValue);
this.upperbound.set(aValue);
this.size.set(1);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean instantiated() {
return size.get() == 1;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(final int aValue) {
return ((aValue >= lowerbound.get()) && (aValue <= upperbound.get()));
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateUpperBound(int aValue) {
size.add(aValue - upperbound.get());
upperbound.set(aValue);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateUpperBoundAndDelta(int aValue) {
boolean change = false;
for (int i = upperbound.get(); i > aValue; i--) {
change = true;
//BEWARE: this line significantly decreases performances
delta.add(i);
}
size.add(aValue - upperbound.get());
upperbound.set(aValue);
return change;
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateLowerBound(int aValue) {
size.add(lowerbound.get() - aValue);
lowerbound.set(aValue);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateLowerBoundAndDelta(int aValue) {
boolean change = false;
for (int i = lowerbound.get(); i < aValue; i++) {
change = true;
//BEWARE: this line significantly decreases performances
delta.add(i);
}
size.add(lowerbound.get() - aValue);
lowerbound.set(aValue);
return change;
}
/**
* {@inheritDoc}
*/
@Override
public boolean empty() {
return size.get() == 0;
}
/**
* {@inheritDoc}
*/
@Override
public int getLB() {
return this.lowerbound.get();
}
/**
* {@inheritDoc}
*/
@Override
public int getUB() {
return this.upperbound.get();
}
/**
* {@inheritDoc}
*/
@Override
public final int getSize() {
return size.get();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEnumerated() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public IntDelta getDelta() {
return delta;
}
/**
* {@inheritDoc}
*/
@Override
public void recordRemoveValues() {
//nothing to do, interval domain does not react on value removals
// TODO: LoggerFactory.getLogger("solver").warn("an adapted delta should be build for bounded domain");
delta = new Delta();
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNextValue(int aValue) {
return aValue < upperbound.get();
}
/**
* {@inheritDoc}
*/
@Override
public int nextValue(final int aValue) {
if (aValue < lowerbound.get()) {
return lowerbound.get();
} else if (aValue < upperbound.get()) {
return aValue + 1;
} else {
return Integer.MAX_VALUE;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasPreviousValue(int aValue) {
return aValue > lowerbound.get();
}
/**
* {@inheritDoc}
*/
@Override
public int previousValue(final int aValue) {
if (aValue > upperbound.get()) {
return upperbound.get();
} else if (aValue > lowerbound.get()) {
return aValue - 1;
} else {
return Integer.MIN_VALUE;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
if (size.get() == 1) {
return Integer.toString(getLB());
}
return String.format("[%d,%d]", getLB(), getUB());
}
}
| solver/src/main/java/solver/variables/domain/IntervalIntDomain.java | /**
* Copyright (c) 1999-2011, Ecole des Mines de Nantes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Ecole des Mines de Nantes nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package solver.variables.domain;
import choco.kernel.common.util.iterators.DisposableIntIterator;
import choco.kernel.memory.IEnvironment;
import choco.kernel.memory.IStateInt;
import org.slf4j.LoggerFactory;
import solver.variables.domain.delta.Delta;
import solver.variables.domain.delta.IntDelta;
import solver.variables.domain.delta.NoDelta;
/**
* <br/>
*
* @author Charles Prud'homme
* @since 28 juil. 2010
*/
public final class IntervalIntDomain implements IIntDomain {
/**
* The backtrackable minimal value of the variable.
*/
private final choco.kernel.memory.IStateInt lowerbound;
/**
* The backtrackable maximal value of the variable.
*/
private final IStateInt upperbound;
private final choco.kernel.memory.IStateInt size;
protected DisposableIntIterator _cachedIterator;
IntDelta delta = NoDelta.singleton;
public IntervalIntDomain(int a, int b, IEnvironment environment) {
lowerbound = environment.makeInt(a);
upperbound = environment.makeInt(b);
size = environment.makeInt(b - a + 1);
// delta = new Delta();
}
/**
* {@inheritDoc}
*/
@Override
public boolean remove(int aValue) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeAndUpdateDelta(int aValue) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean restrictAndUpdateDelta(int aValue) {
int ub = this.upperbound.get();
int i = this.lowerbound.get();
for (; i < aValue; i++) {
delta.add(i);
}
i = aValue+1;
for (; i <= ub; i++) {
delta.add(i);
}
this.lowerbound.set(aValue);
this.upperbound.set(aValue);
boolean change = size.get() > 1;
this.size.set(1);
return change;
}
/**
* {@inheritDoc}
*/
@Override
public boolean restrict(int aValue) {
this.lowerbound.set(aValue);
this.upperbound.set(aValue);
this.size.set(1);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean instantiated() {
return size.get() == 1;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(final int aValue) {
return ((aValue >= lowerbound.get()) && (aValue <= upperbound.get()));
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateUpperBound(int aValue) {
size.add(aValue - upperbound.get());
upperbound.set(aValue);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateUpperBoundAndDelta(int aValue) {
boolean change = false;
for (int i = upperbound.get(); i > aValue; i--) {
change = true;
//BEWARE: this line significantly decreases performances
delta.add(i);
}
size.add(aValue - upperbound.get());
upperbound.set(aValue);
return change;
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateLowerBound(int aValue) {
size.add(lowerbound.get() - aValue);
lowerbound.set(aValue);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateLowerBoundAndDelta(int aValue) {
boolean change = false;
for (int i = lowerbound.get(); i < aValue; i++) {
change = true;
//BEWARE: this line significantly decreases performances
delta.add(i);
}
size.add(lowerbound.get() - aValue);
lowerbound.set(aValue);
return change;
}
/**
* {@inheritDoc}
*/
@Override
public boolean empty() {
return size.get() == 0;
}
/**
* {@inheritDoc}
*/
@Override
public int getLB() {
return this.lowerbound.get();
}
/**
* {@inheritDoc}
*/
@Override
public int getUB() {
return this.upperbound.get();
}
/**
* {@inheritDoc}
*/
@Override
public final int getSize() {
return size.get();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEnumerated() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public IntDelta getDelta() {
return delta;
}
/**
* {@inheritDoc}
*/
@Override
public void recordRemoveValues() {
//nothing to do, interval domain does not react on value removals
LoggerFactory.getLogger("solver").warn("an adapted delta should be build for bounded domain");
delta = new Delta();
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNextValue(int aValue) {
return aValue < upperbound.get();
}
/**
* {@inheritDoc}
*/
@Override
public int nextValue(final int aValue) {
if (aValue < lowerbound.get()) {
return lowerbound.get();
} else if (aValue < upperbound.get()) {
return aValue + 1;
} else {
return Integer.MAX_VALUE;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasPreviousValue(int aValue) {
return aValue > lowerbound.get();
}
/**
* {@inheritDoc}
*/
@Override
public int previousValue(final int aValue) {
if (aValue > upperbound.get()) {
return upperbound.get();
} else if (aValue > lowerbound.get()) {
return aValue - 1;
} else {
return Integer.MIN_VALUE;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
if (size.get() == 1) {
return Integer.toString(getLB());
}
return String.format("[%d,%d]", getLB(), getUB());
}
}
| - remove warning message in IntervalIntDomain
git-svn-id: 0c0af4c802c9e8f057426f0050753a5c49b12902@395 031d3fc5-a07f-0410-aa2d-fafe74bc0a1b
| solver/src/main/java/solver/variables/domain/IntervalIntDomain.java | - remove warning message in IntervalIntDomain | <ide><path>olver/src/main/java/solver/variables/domain/IntervalIntDomain.java
<ide> import choco.kernel.common.util.iterators.DisposableIntIterator;
<ide> import choco.kernel.memory.IEnvironment;
<ide> import choco.kernel.memory.IStateInt;
<del>import org.slf4j.LoggerFactory;
<ide> import solver.variables.domain.delta.Delta;
<ide> import solver.variables.domain.delta.IntDelta;
<ide> import solver.variables.domain.delta.NoDelta;
<ide> @Override
<ide> public void recordRemoveValues() {
<ide> //nothing to do, interval domain does not react on value removals
<del> LoggerFactory.getLogger("solver").warn("an adapted delta should be build for bounded domain");
<add>// TODO: LoggerFactory.getLogger("solver").warn("an adapted delta should be build for bounded domain");
<ide> delta = new Delta();
<ide> }
<ide> |
|
Java | apache-2.0 | 19a96190b0eaf29c9d8a21d8b2ce4d5cfcb3c8c9 | 0 | Squarespace/template-compiler,phensley/template-compiler,Squarespace/template-compiler,phensley/template-compiler,phensley/template-compiler,Squarespace/template-compiler | /**
* Copyright, 2015, Squarespace, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squarespace.template.cli;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.apache.commons.io.IOUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.squarespace.template.BuildProperties;
import com.squarespace.template.CodeException;
import com.squarespace.template.CompiledTemplate;
import com.squarespace.template.Compiler;
import com.squarespace.template.Context;
import com.squarespace.template.ErrorInfo;
import com.squarespace.template.FormatterTable;
import com.squarespace.template.GeneralUtils;
import com.squarespace.template.Instruction;
import com.squarespace.template.JsonUtils;
import com.squarespace.template.PredicateTable;
import com.squarespace.template.ReferenceScanner;
import com.squarespace.template.TreeEmitter;
import com.squarespace.template.plugins.CoreFormatters;
import com.squarespace.template.plugins.CorePredicates;
import com.squarespace.template.plugins.platform.CommerceFormatters;
import com.squarespace.template.plugins.platform.CommercePredicates;
import com.squarespace.template.plugins.platform.ContentFormatters;
import com.squarespace.template.plugins.platform.ContentPredicates;
import com.squarespace.template.plugins.platform.SlidePredicates;
import com.squarespace.template.plugins.platform.SocialFormatters;
import com.squarespace.template.plugins.platform.SocialPredicates;
import com.squarespace.template.plugins.platform.i18n.InternationalFormatters;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
/**
* Command line template compiler.
*/
public class TemplateC {
private static final String TEMPLATE_REPOSITORY = "http://github.com/squarespace/squarespace-template";
private static final String PROGRAM_NAME = "templatec";
public static void main(String[] args) {
TemplateC command = new TemplateC();
command.execute(args);
}
protected void execute(String[] args) {
String version = buildVersion();
ArgumentParser parser = ArgumentParsers.newArgumentParser(PROGRAM_NAME)
.description("Compile template files")
.version(version);
parser.addArgument("--version", "-v")
.action(Arguments.version())
.help("Show the version and exit");
parser.addArgument("--stats", "-s")
.action(Arguments.storeTrue())
.help("Dump stats for the template");
parser.addArgument("--tree", "-t")
.action(Arguments.storeTrue())
.help("Dump the syntax tree for the template");
parser.addArgument("--json", "-j")
.type(String.class)
.help("JSON tree");
parser.addArgument("--partials", "-p")
.type(String.class)
.help("JSON partials");
parser.addArgument("template")
.type(String.class)
.help("Template source");
int exitCode = 1;
try {
Namespace res = parser.parseArgs(args);
if (res.getBoolean("stats")) {
exitCode = stats(res.getString("template"));
} else if (res.getBoolean("tree")) {
exitCode = tree(res.getString("template"));
} else {
exitCode = compile(res.getString("template"), res.getString("json"), res.getString("partials"));
}
} catch (CodeException | IOException e) {
System.err.println(e.getMessage());
} catch (ArgumentParserException e) {
parser.handleError(e);
System.exit(1);
} finally {
System.exit(exitCode);
}
}
/**
* Compile a template against a given json tree and emit the result.
*/
protected int compile(String templatePath, String jsonPath, String partialsPath)
throws CodeException, IOException {
String template = readFile(templatePath);
String json = "{}";
if (jsonPath != null) {
json = readFile(jsonPath);
}
String partials = null;
if (partialsPath != null) {
partials = readFile(partialsPath);
}
CompiledTemplate compiled = compiler().compile(template, true);
StringBuilder errorBuf = new StringBuilder();
List<ErrorInfo> errors = compiled.errors();
if (!errors.isEmpty()) {
errorBuf.append("Caught errors executing template:\n");
for (ErrorInfo error : errors) {
errorBuf.append(" ").append(error.getMessage()).append('\n');
}
}
Instruction code = compiled.code();
// Parse the JSON context
JsonNode jsonTree = null;
try {
jsonTree = JsonUtils.decode(json);
} catch (IllegalArgumentException e) {
System.err.println("Caught error trying to parse JSON: " + e.getCause().getMessage());
return 1;
}
// Parse the optional JSON partials dictionary.
JsonNode partialsTree = null;
if (partials != null) {
try {
partialsTree = JsonUtils.decode(partials);
if (!(partialsTree instanceof ObjectNode)) {
System.err.println("Partials map JSON must be an object. Found " + partialsTree.getNodeType());
return 1;
}
} catch (IllegalArgumentException e) {
System.err.println("Caught error trying to parse partials: " + e.getCause().getMessage());
return 1;
}
}
// Perform the compile.
Context context = compiler().newExecutor()
.code(code)
.json(jsonTree)
.safeExecution(true)
.partialsMap((ObjectNode)partialsTree)
.execute();
// If compile was successful, print the output.
System.out.print(context.buffer().toString());
if (errorBuf.length() > 0) {
System.err.println(errorBuf.toString());
}
return 0;
}
/**
* Scan the compiled template and print statistics.
*/
protected int stats(String templatePath) throws CodeException, IOException {
String template = readFile(templatePath);
CompiledTemplate compiled = compiler().compile(template, false);
ReferenceScanner scanner = new ReferenceScanner();
scanner.extract(compiled.code());
ObjectNode report = scanner.references().report();
String result = GeneralUtils.jsonPretty(report);
System.out.println(result);
return 0;
}
/**
* Print the syntax tree for the given template.
*/
protected int tree(String templatePath) throws CodeException, IOException {
String template = readFile(templatePath);
CompiledTemplate compiled = compiler().compile(template, false);
StringBuilder buf = new StringBuilder();
TreeEmitter.emit(compiled.code(), 0, buf);
System.out.println(buf.toString());
return 0;
}
protected Compiler compiler() {
FormatterTable formatterTable = new FormatterTable();
PredicateTable predicateTable = new PredicateTable();
// core
formatterTable.register(new CoreFormatters());
predicateTable.register(new CorePredicates());
// TODO: dynamic classpath scan and registration of plugin jars.
// squarespace
formatterTable.register(new CommerceFormatters());
formatterTable.register(new ContentFormatters());
formatterTable.register(new SocialFormatters());
formatterTable.register(new InternationalFormatters());
predicateTable.register(new CommercePredicates());
predicateTable.register(new ContentPredicates());
predicateTable.register(new SlidePredicates());
predicateTable.register(new SocialPredicates());
return new Compiler(formatterTable, predicateTable);
}
protected String readFile(String rawPath) throws IOException {
try (Reader reader = new InputStreamReader(new FileInputStream(rawPath), "UTF-8")) {
return IOUtils.toString(reader);
}
}
/**
* Build the version string.
*/
protected String buildVersion() {
StringBuilder buf = new StringBuilder();
buf.append("${prog} version ")
.append(BuildProperties.version())
.append('\n');
buf.append(" repository: ").append(TEMPLATE_REPOSITORY).append('\n');
buf.append(" build date: ").append(BuildProperties.date()).append('\n');
buf.append(" build commit: ").append(BuildProperties.commit()).append('\n');
return buf.toString();
}
}
| cli/src/main/java/com/squarespace/template/cli/TemplateC.java | /**
* Copyright, 2015, Squarespace, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squarespace.template.cli;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.commons.io.IOUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.squarespace.template.BuildProperties;
import com.squarespace.template.CodeException;
import com.squarespace.template.CompiledTemplate;
import com.squarespace.template.Compiler;
import com.squarespace.template.Context;
import com.squarespace.template.FormatterTable;
import com.squarespace.template.GeneralUtils;
import com.squarespace.template.Instruction;
import com.squarespace.template.JsonUtils;
import com.squarespace.template.PredicateTable;
import com.squarespace.template.ReferenceScanner;
import com.squarespace.template.TreeEmitter;
import com.squarespace.template.plugins.CoreFormatters;
import com.squarespace.template.plugins.CorePredicates;
import com.squarespace.template.plugins.platform.CommerceFormatters;
import com.squarespace.template.plugins.platform.CommercePredicates;
import com.squarespace.template.plugins.platform.ContentFormatters;
import com.squarespace.template.plugins.platform.ContentPredicates;
import com.squarespace.template.plugins.platform.SlidePredicates;
import com.squarespace.template.plugins.platform.SocialFormatters;
import com.squarespace.template.plugins.platform.SocialPredicates;
import com.squarespace.template.plugins.platform.i18n.InternationalFormatters;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
/**
* Command line template compiler.
*/
public class TemplateC {
private static final String TEMPLATE_REPOSITORY = "http://github.com/squarespace/squarespace-template";
private static final String PROGRAM_NAME = "templatec";
public static void main(String[] args) {
TemplateC command = new TemplateC();
command.execute(args);
}
protected void execute(String[] args) {
String version = buildVersion();
ArgumentParser parser = ArgumentParsers.newArgumentParser(PROGRAM_NAME)
.description("Compile template files")
.version(version);
parser.addArgument("--version", "-v")
.action(Arguments.version())
.help("Show the version and exit");
parser.addArgument("--stats", "-s")
.action(Arguments.storeTrue())
.help("Dump stats for the template");
parser.addArgument("--tree", "-t")
.action(Arguments.storeTrue())
.help("Dump the syntax tree for the template");
parser.addArgument("--json", "-j")
.type(String.class)
.help("JSON tree");
parser.addArgument("--partials", "-p")
.type(String.class)
.help("JSON partials");
parser.addArgument("template")
.type(String.class)
.help("Template source");
int exitCode = 1;
try {
Namespace res = parser.parseArgs(args);
if (res.getBoolean("stats")) {
exitCode = stats(res.getString("template"));
} else if (res.getBoolean("tree")) {
exitCode = tree(res.getString("template"));
} else {
exitCode = compile(res.getString("template"), res.getString("json"), res.getString("partials"));
}
} catch (CodeException | IOException e) {
System.err.println(e.getMessage());
} catch (ArgumentParserException e) {
parser.handleError(e);
System.exit(1);
} finally {
System.exit(exitCode);
}
}
/**
* Compile a template against a given json tree and emit the result.
*/
protected int compile(String templatePath, String jsonPath, String partialsPath)
throws CodeException, IOException {
String template = readFile(templatePath);
String json = "{}";
if (jsonPath != null) {
json = readFile(jsonPath);
}
String partials = null;
if (partialsPath != null) {
partials = readFile(partialsPath);
}
CompiledTemplate compiled = compiler().compile(template, false);
Instruction code = compiled.code();
// Parse the JSON context
JsonNode jsonTree = null;
try {
jsonTree = JsonUtils.decode(json);
} catch (IllegalArgumentException e) {
System.err.println("Caught error trying to parse JSON: " + e.getCause().getMessage());
return 1;
}
// Parse the optional JSON partials dictionary.
JsonNode partialsTree = null;
if (partials != null) {
try {
partialsTree = JsonUtils.decode(partials);
if (!(partialsTree instanceof ObjectNode)) {
System.err.println("Partials map JSON must be an object. Found " + partialsTree.getNodeType());
return 1;
}
} catch (IllegalArgumentException e) {
System.err.println("Caught error trying to parse partials: " + e.getCause().getMessage());
return 1;
}
}
// Perform the compile.
Context context = compiler().newExecutor()
.code(code)
.json(jsonTree)
.partialsMap((ObjectNode)partialsTree)
.execute();
// If compile was successful, print the output.
System.out.print(context.buffer().toString());
return 0;
}
/**
* Scan the compiled template and print statistics.
*/
protected int stats(String templatePath) throws CodeException, IOException {
String template = readFile(templatePath);
CompiledTemplate compiled = compiler().compile(template, false);
ReferenceScanner scanner = new ReferenceScanner();
scanner.extract(compiled.code());
ObjectNode report = scanner.references().report();
String result = GeneralUtils.jsonPretty(report);
System.out.println(result);
return 0;
}
/**
* Print the syntax tree for the given template.
*/
protected int tree(String templatePath) throws CodeException, IOException {
String template = readFile(templatePath);
CompiledTemplate compiled = compiler().compile(template, false);
StringBuilder buf = new StringBuilder();
TreeEmitter.emit(compiled.code(), 0, buf);
System.out.println(buf.toString());
return 0;
}
protected Compiler compiler() {
FormatterTable formatterTable = new FormatterTable();
PredicateTable predicateTable = new PredicateTable();
// core
formatterTable.register(new CoreFormatters());
predicateTable.register(new CorePredicates());
// TODO: dynamic classpath scan and registration of plugin jars.
// squarespace
formatterTable.register(new CommerceFormatters());
formatterTable.register(new ContentFormatters());
formatterTable.register(new SocialFormatters());
formatterTable.register(new InternationalFormatters());
predicateTable.register(new CommercePredicates());
predicateTable.register(new ContentPredicates());
predicateTable.register(new SlidePredicates());
predicateTable.register(new SocialPredicates());
return new Compiler(formatterTable, predicateTable);
}
protected String readFile(String rawPath) throws IOException {
try (Reader reader = new InputStreamReader(new FileInputStream(rawPath), "UTF-8")) {
return IOUtils.toString(reader);
}
}
/**
* Build the version string.
*/
protected String buildVersion() {
StringBuilder buf = new StringBuilder();
buf.append("${prog} version ")
.append(BuildProperties.version())
.append('\n');
buf.append(" repository: ").append(TEMPLATE_REPOSITORY).append('\n');
buf.append(" build date: ").append(BuildProperties.date()).append('\n');
buf.append(" build commit: ").append(BuildProperties.commit()).append('\n');
return buf.toString();
}
}
| CLI display compilation errors on stderr.
| cli/src/main/java/com/squarespace/template/cli/TemplateC.java | CLI display compilation errors on stderr. | <ide><path>li/src/main/java/com/squarespace/template/cli/TemplateC.java
<ide> import java.io.IOException;
<ide> import java.io.InputStreamReader;
<ide> import java.io.Reader;
<add>import java.util.List;
<ide>
<ide> import org.apache.commons.io.IOUtils;
<ide>
<ide> import com.squarespace.template.CompiledTemplate;
<ide> import com.squarespace.template.Compiler;
<ide> import com.squarespace.template.Context;
<add>import com.squarespace.template.ErrorInfo;
<ide> import com.squarespace.template.FormatterTable;
<ide> import com.squarespace.template.GeneralUtils;
<ide> import com.squarespace.template.Instruction;
<ide> partials = readFile(partialsPath);
<ide> }
<ide>
<del> CompiledTemplate compiled = compiler().compile(template, false);
<add> CompiledTemplate compiled = compiler().compile(template, true);
<add>
<add> StringBuilder errorBuf = new StringBuilder();
<add> List<ErrorInfo> errors = compiled.errors();
<add> if (!errors.isEmpty()) {
<add> errorBuf.append("Caught errors executing template:\n");
<add> for (ErrorInfo error : errors) {
<add> errorBuf.append(" ").append(error.getMessage()).append('\n');
<add> }
<add> }
<add>
<ide> Instruction code = compiled.code();
<ide>
<ide> // Parse the JSON context
<ide> Context context = compiler().newExecutor()
<ide> .code(code)
<ide> .json(jsonTree)
<add> .safeExecution(true)
<ide> .partialsMap((ObjectNode)partialsTree)
<ide> .execute();
<ide>
<ide> // If compile was successful, print the output.
<ide> System.out.print(context.buffer().toString());
<add>
<add> if (errorBuf.length() > 0) {
<add> System.err.println(errorBuf.toString());
<add> }
<ide> return 0;
<ide> }
<ide> |
|
JavaScript | mit | 05c4d396e6b269203365b20e91910ce09bf92d6f | 0 | DawidMyslak/kubernetes-helm-ui,DawidMyslak/kubernetes-helm-ui | import Vue from 'vue'
import Vuex from 'vuex'
import kube from './tools/kube'
import helm from './tools/helm'
Vue.use(Vuex)
const state = {
context: { name: null },
contexts: [],
namespace: { name: null },
namespaces: [],
release: { name: null },
releases: [],
history: [],
config: {
kubePath: '/usr/local/bin/',
helmPath: '/usr/local/bin/'
},
logs: []
}
const mutations = {
SET_CONTEXT(state, context) {
state.context = context
},
RESET_CONTEXT_DEPENDENCIES(state) {
state.namespace.name = null
state.namespaces = []
state.release.name = null
state.releases = []
state.history = []
},
SET_CONTEXTS(state, contexts) {
state.contexts = contexts
},
SET_NAMESPACE(state, namespace) {
state.namespace = namespace
},
RESET_NAMESPACE_DEPENDENCIES(state) {
state.release.name = null
state.releases = []
state.history = []
},
SET_NAMESPACES(state, namespaces) {
state.namespaces = namespaces
},
SET_RELEASE(state, release) {
state.release = release
},
RESET_RELEASE_DEPENDENCIES(state) {
state.history = []
},
SET_RELEASES(state, releases) {
state.releases = releases
},
SET_HISTORY(state, history) {
state.history = history
},
SET_CONFIG(state, config) {
state.config = config
},
ADD_LOG(state, log) {
state.logs.push(log)
}
}
const actions = {
applyContext({ commit }, context) {
return kube.useContext(context.name)
.then(() => {
commit('SET_CONTEXT', context)
commit('RESET_CONTEXT_DEPENDENCIES')
})
},
loadContexts({ commit }) {
return kube.getContexts()
.then((contexts) => {
commit('SET_CONTEXTS', contexts)
const context = contexts.find((context) => context.current === '*')
commit('SET_CONTEXT', context)
})
},
applyNamespace({ commit }, namespace) {
commit('SET_NAMESPACE', namespace)
commit('RESET_NAMESPACE_DEPENDENCIES')
return Promise.resolve()
},
loadNamespaces({ commit }) {
return kube.getNamespaces()
.then((namespaces) => {
commit('SET_NAMESPACES', namespaces)
const namespace = namespaces[0]
commit('SET_NAMESPACE', namespace)
})
},
applyRelease({ commit }, release) {
commit('SET_RELEASE', release)
commit('RESET_RELEASE_DEPENDENCIES')
return Promise.resolve()
},
loadReleases({ commit, state }) {
return helm.getReleases(state.namespace.name)
.then((releases) => {
commit('SET_RELEASES', releases)
})
},
loadHistory({ commit, state }) {
return helm.getHistory(state.release.name, state.namespace.name)
.then((history) => {
commit('SET_HISTORY', history.reverse())
})
},
applyConfig({ commit }, config) {
commit('SET_CONFIG', config)
return Promise.resolve()
},
addLog({ commit }, log) {
commit('ADD_LOG', log)
return Promise.resolve()
}
}
export default new Vuex.Store({
state,
mutations,
actions,
strict: process.env.NODE_ENV !== 'production'
})
| src/renderer/store.js | import Vue from 'vue'
import Vuex from 'vuex'
import kube from './tools/kube'
import helm from './tools/helm'
Vue.use(Vuex)
const state = {
context: { name: null },
contexts: [],
namespace: { name: null },
namespaces: [],
release: { name: null },
releases: [],
history: [],
config: {
kubePath: '/usr/local/bin/',
helmPath: '/usr/local/bin/'
},
logs: []
}
const mutations = {
SET_CONTEXT(state, context) {
state.context = context
},
RESET_CONTEXT_DEPENDENCIES(state) {
state.namespace.name = null
state.namespaces = []
state.release.name = null
state.releases = []
state.history = []
},
SET_CONTEXTS(state, contexts) {
state.contexts = contexts
},
SET_NAMESPACE(state, namespace) {
state.namespace = namespace
},
RESET_NAMESPACE_DEPENDENCIES(state) {
state.release.name = null
state.releases = []
state.history = []
},
SET_NAMESPACES(state, namespaces) {
state.namespaces = namespaces
},
SET_RELEASE(state, release) {
state.release = release
},
RESET_RELEASE_DEPENDENCIES(state) {
state.history = []
},
SET_RELEASES(state, releases) {
state.releases = releases
},
SET_HISTORY(state, history) {
state.history = history
},
SET_CONFIG(state, config) {
state.config = config
},
ADD_LOG(state, log) {
state.logs.push(log)
}
}
const actions = {
applyContext({ commit }, context) {
return kube.useContext(context.name)
.then(() => {
commit('SET_CONTEXT', context)
commit('RESET_CONTEXT_DEPENDENCIES')
})
},
loadContexts({ commit }) {
return kube.getContexts()
.then((contexts) => {
commit('SET_CONTEXTS', contexts)
let context = contexts.find((context) => context.current === '*')
commit('SET_CONTEXT', context)
})
},
applyNamespace({ commit }, namespace) {
commit('SET_NAMESPACE', namespace)
commit('RESET_NAMESPACE_DEPENDENCIES')
return Promise.resolve()
},
loadNamespaces({ commit }) {
return kube.getNamespaces()
.then((namespaces) => {
commit('SET_NAMESPACES', namespaces)
let namespace = namespaces[0]
commit('SET_NAMESPACE', namespace)
})
},
applyRelease({ commit }, release) {
commit('SET_RELEASE', release)
commit('RESET_RELEASE_DEPENDENCIES')
return Promise.resolve()
},
loadReleases({ commit, state }) {
return helm.getReleases(state.namespace.name)
.then((releases) => {
commit('SET_RELEASES', releases)
})
},
loadHistory({ commit, state }) {
return helm.getHistory(state.release.name, state.namespace.name)
.then((history) => {
commit('SET_HISTORY', history.reverse())
})
},
applyConfig({ commit }, config) {
commit('SET_CONFIG', config)
return Promise.resolve()
},
addLog({ commit }, log) {
commit('ADD_LOG', log)
return Promise.resolve()
}
}
export default new Vuex.Store({
state,
mutations,
actions,
strict: process.env.NODE_ENV !== 'production'
})
| let to const
| src/renderer/store.js | let to const | <ide><path>rc/renderer/store.js
<ide> .then((contexts) => {
<ide> commit('SET_CONTEXTS', contexts)
<ide>
<del> let context = contexts.find((context) => context.current === '*')
<add> const context = contexts.find((context) => context.current === '*')
<ide> commit('SET_CONTEXT', context)
<ide> })
<ide> },
<ide> .then((namespaces) => {
<ide> commit('SET_NAMESPACES', namespaces)
<ide>
<del> let namespace = namespaces[0]
<add> const namespace = namespaces[0]
<ide> commit('SET_NAMESPACE', namespace)
<ide> })
<ide> }, |
|
Java | apache-2.0 | 4b2846308dace7dc8de23793e07c6b4b8c89a525 | 0 | ontopia/ontopia,ontopia/ontopia,ontopia/ontopia,ontopia/ontopia,ontopia/ontopia |
// $Id: RDBMSSingleTopicMapSource.java,v 1.25 2008/12/04 14:58:04 geir.gronmo Exp $
package net.ontopia.topicmaps.impl.rdbms;
import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.*;
import java.util.*;
import net.ontopia.utils.*;
import net.ontopia.topicmaps.entry.*;
import net.ontopia.topicmaps.utils.*;
import net.ontopia.infoset.core.LocatorIF;
import net.ontopia.infoset.core.Locators;
import net.ontopia.infoset.impl.basic.URILocator;
import net.ontopia.persistence.proxy.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* PUBLIC: A topic map source that holds a reference to a single rdbms
* topic map. Individual topic maps can thus be pointed to by this
* source implementation.<p>
*
* @since 1.3.4
*/
public class RDBMSSingleTopicMapSource implements TopicMapSourceIF {
protected String id;
protected String referenceId;
protected String title;
protected String propfile;
protected long topicmap_id;
protected LocatorIF base_address;
protected boolean hidden;
protected String topicListeners;
protected RDBMSTopicMapReference reference;
// Define a logging category.
static Logger log = LoggerFactory.getLogger(RDBMSSingleTopicMapSource.class.getName());
// --- TopicMapSourceIF implementation
public TopicMapReferenceIF createTopicMap(String name, String baseAddress) {
throw new UnsupportedOperationException();
}
public synchronized Collection getReferences() {
if (reference == null) refresh();
if (reference == null) return Collections.EMPTY_SET;
return Collections.singleton(reference);
}
public synchronized void refresh() {
// FIXME: for now don't recreate reference if already exists
if (reference != null) return;
boolean foundReference = false;
try {
RDBMSStorage storage = createStorage();
String _title = title;
LocatorIF _base_address = base_address;
// retrieve reference id from database
if (_title == null || _base_address == null) {
Connection conn = conn = storage.getConnectionFactory(true).requestConnection();
try {
PreparedStatement stm = conn.prepareStatement("select M.title, M.base_address from TM_TOPIC_MAP M where M.id = ?");
try {
stm.setLong(1, topicmap_id);
ResultSet rs = stm.executeQuery();
if (rs.next()) {
foundReference = true;
if (_title == null)
_title = rs.getString(1);
if (_base_address == null) {
String loc = rs.getString(2);
if (loc != null)
_base_address = Locators.getURILocator(loc);
}
}
rs.close();
} finally {
stm.close();
}
} catch (Exception e) {
throw new OntopiaRuntimeException(e);
} finally {
try { conn.close(); } catch (Exception e) { };
}
}
// create a reference id if not already exists
if (foundReference) {
String _referenceId = this.referenceId;
if (_referenceId == null)
_referenceId = getReferenceId(topicmap_id);
// use reference id as title if not otherwise found
_title = (_title != null ? _title : _referenceId);
log.debug("Created new reference '" + _referenceId + "' to topic map " + topicmap_id);
RDBMSTopicMapReference ref = new RDBMSTopicMapReference(_referenceId, _title, storage, topicmap_id, _base_address);
ref.setSource(this);
// register topic listeners
if (topicListeners != null)
ref.registerTopicListeners(topicListeners);
this.reference = ref;
} else {
log.info("Could not create reference for single RDBMS source " +
id + " because no topic map found");
this.reference = null;
}
} catch (Exception e) {
throw new OntopiaRuntimeException(e);
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean supportsCreate() {
return false;
}
public boolean supportsDelete() {
return false;
}
// --- Internal helpers
protected RDBMSStorage createStorage() throws IOException {
if (propfile == null)
throw new OntopiaRuntimeException("propertyFile property must be specified on source with id '" + getId() + "'.");
return new RDBMSStorage(propfile);
}
protected String getReferenceId(long topicmap_id) {
if (id == null)
return "RDBMS-" + topicmap_id;
else
return id + "-" + topicmap_id;
}
// --- Extension properties
/**
* PUBLIC: Gets the database property file containing configuration
* parameters for accessing the rdbms database.
*/
public String getPropertyFile() {
return propfile;
}
/**
* PUBLIC: Sets the database property file containing configuration
* parameters for accessing the rdbms database. The propfile given
* with first be attempted loaded from the file system. If it does
* not exist on the file system it will be loaded from the
* classpath. If the access must be explicit then the property file
* name can be prefixed by 'file:' or 'classpath:'.
*/
public void setPropertyFile(String propfile) {
this.propfile = propfile;
}
/**
* PUBLIC: Gets the id of the topic map referenced. Note that this
* id must be the string representation of a long.
*/
public String getTopicMapId() {
return Long.toString(topicmap_id);
}
/**
* PUBLIC: Sets the id of the topic map referenced. Note that this
* id must be the string representation of a long.
*/
public void setTopicMapId(String id) {
// strip out 'M'
if (id.charAt(0) == 'M')
setTopicMapId(Long.parseLong(id.substring(1)));
else
setTopicMapId(Long.parseLong(id));
}
/**
* PUBLIC: Sets the id of the topic map referenced.
*/
public void setTopicMapId(long id) {
this.topicmap_id = id;
}
/**
* INTERNAL: Gets the alias of the topic map reference.
*
* @deprecated Replaced by getReferenceId().
*/
public String getAlias() {
return getReferenceId();
}
/**
* INTERNAL: Sets the alias of the topic map reference.
*
* @deprecated Replaced by setReferenceId(String).
*/
public void setAlias(String alias) {
setReferenceId(alias);
}
/**
* PUBLIC: Gets the id of the topic map reference for this topic map
* source.
*/
public String getReferenceId() {
return referenceId;
}
/**
* PUBLIC: Sets the id of the topic map reference for this topic map
* source.
*/
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
/**
* PUBLIC: Gets the base address of the topic maps retrieved from
* the source. The notation is assumed to be 'URI'.
*/
public String getBaseAddress() {
return (base_address == null ? null : base_address.getAddress());
}
/**
* PUBLIC: Sets the base address of the topic maps retrieved from
* the source. The notation is assumed to be 'URI'.
*/
public void setBaseAddress(String base_address) {
try {
this.base_address = new URILocator(base_address);
} catch (MalformedURLException e) {
throw new OntopiaRuntimeException(e);
}
}
public boolean getHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public String getTopicListeners() {
return topicListeners;
}
public void setTopicListeners(String topicListeners) {
this.topicListeners = topicListeners;
}
}
| ontopia/src/java/net/ontopia/topicmaps/impl/rdbms/RDBMSSingleTopicMapSource.java |
// $Id: RDBMSSingleTopicMapSource.java,v 1.25 2008/12/04 14:58:04 geir.gronmo Exp $
package net.ontopia.topicmaps.impl.rdbms;
import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.*;
import java.util.*;
import net.ontopia.utils.*;
import net.ontopia.topicmaps.entry.*;
import net.ontopia.topicmaps.utils.*;
import net.ontopia.infoset.core.LocatorIF;
import net.ontopia.infoset.core.Locators;
import net.ontopia.infoset.impl.basic.URILocator;
import net.ontopia.persistence.proxy.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* PUBLIC: A topic map source that holds a reference to a single rdbms
* topic map. Individual topic maps can thus be pointed to by this
* source implementation.<p>
*
* @since 1.3.4
*/
public class RDBMSSingleTopicMapSource implements TopicMapSourceIF {
protected String id;
protected String referenceId;
protected String title;
protected String propfile;
protected long topicmap_id;
protected LocatorIF base_address;
protected boolean hidden;
protected String topicListeners;
protected RDBMSTopicMapReference reference;
// Define a logging category.
static Logger log = LoggerFactory.getLogger(RDBMSSingleTopicMapSource.class.getName());
// --- TopicMapSourceIF implementation
public TopicMapReferenceIF createTopicMap(String name, String baseAddress) {
throw new UnsupportedOperationException();
}
public synchronized Collection getReferences() {
if (reference == null) refresh();
if (reference == null) return Collections.EMPTY_SET;
return Collections.singleton(reference);
}
public synchronized void refresh() {
// FIXME: for now don't recreate reference if already exists
if (reference != null) return;
boolean foundReference = false;
try {
RDBMSStorage storage = createStorage();
String _title = title;
LocatorIF _base_address = base_address;
// retrieve reference id from database
if (_title == null || _base_address == null) {
Connection conn = conn = storage.getConnectionFactory(true).requestConnection();
try {
PreparedStatement stm = conn.prepareStatement("select M.title, M.base_address from TM_TOPIC_MAP M where M.id = ?");
try {
stm.setLong(1, topicmap_id);
ResultSet rs = stm.executeQuery();
if (rs.next()) {
foundReference = true;
if (_title == null)
_title = rs.getString(1);
if (_base_address == null) {
String loc = rs.getString(2);
if (loc != null)
_base_address = Locators.getURILocator(loc);
}
}
rs.close();
} finally {
stm.close();
}
} catch (Exception e) {
throw new OntopiaRuntimeException(e);
} finally {
try { conn.close(); } catch (Exception e) { };
}
}
// create a reference id if not already exists
if (foundReference) {
String _referenceId = this.referenceId;
if (_referenceId == null)
_referenceId = getReferenceId(topicmap_id);
// use reference id as title if not otherwise found
_title = (_title != null ? _title : _referenceId);
log.debug("Created new reference '" + _referenceId + "' to topic map " + topicmap_id);
RDBMSTopicMapReference ref = new RDBMSTopicMapReference(_referenceId, _title, storage, topicmap_id, _base_address);
ref.setSource(this);
// register topic listeners
if (topicListeners != null)
ref.registerTopicListeners(topicListeners);
this.reference = ref;
} else {
this.reference = null;
}
} catch (Exception e) {
throw new OntopiaRuntimeException(e);
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean supportsCreate() {
return false;
}
public boolean supportsDelete() {
return false;
}
// --- Internal helpers
protected RDBMSStorage createStorage() throws IOException {
if (propfile == null)
throw new OntopiaRuntimeException("propertyFile property must be specified on source with id '" + getId() + "'.");
return new RDBMSStorage(propfile);
}
protected String getReferenceId(long topicmap_id) {
if (id == null)
return "RDBMS-" + topicmap_id;
else
return id + "-" + topicmap_id;
}
// --- Extension properties
/**
* PUBLIC: Gets the database property file containing configuration
* parameters for accessing the rdbms database.
*/
public String getPropertyFile() {
return propfile;
}
/**
* PUBLIC: Sets the database property file containing configuration
* parameters for accessing the rdbms database. The propfile given
* with first be attempted loaded from the file system. If it does
* not exist on the file system it will be loaded from the
* classpath. If the access must be explicit then the property file
* name can be prefixed by 'file:' or 'classpath:'.
*/
public void setPropertyFile(String propfile) {
this.propfile = propfile;
}
/**
* PUBLIC: Gets the id of the topic map referenced. Note that this
* id must be the string representation of a long.
*/
public String getTopicMapId() {
return Long.toString(topicmap_id);
}
/**
* PUBLIC: Sets the id of the topic map referenced. Note that this
* id must be the string representation of a long.
*/
public void setTopicMapId(String id) {
// strip out 'M'
if (id.charAt(0) == 'M')
setTopicMapId(Long.parseLong(id.substring(1)));
else
setTopicMapId(Long.parseLong(id));
}
/**
* PUBLIC: Sets the id of the topic map referenced.
*/
public void setTopicMapId(long id) {
this.topicmap_id = id;
}
/**
* INTERNAL: Gets the alias of the topic map reference.
*
* @deprecated Replaced by getReferenceId().
*/
public String getAlias() {
return getReferenceId();
}
/**
* INTERNAL: Sets the alias of the topic map reference.
*
* @deprecated Replaced by setReferenceId(String).
*/
public void setAlias(String alias) {
setReferenceId(alias);
}
/**
* PUBLIC: Gets the id of the topic map reference for this topic map
* source.
*/
public String getReferenceId() {
return referenceId;
}
/**
* PUBLIC: Sets the id of the topic map reference for this topic map
* source.
*/
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
/**
* PUBLIC: Gets the base address of the topic maps retrieved from
* the source. The notation is assumed to be 'URI'.
*/
public String getBaseAddress() {
return (base_address == null ? null : base_address.getAddress());
}
/**
* PUBLIC: Sets the base address of the topic maps retrieved from
* the source. The notation is assumed to be 'URI'.
*/
public void setBaseAddress(String base_address) {
try {
this.base_address = new URILocator(base_address);
} catch (MalformedURLException e) {
throw new OntopiaRuntimeException(e);
}
}
public boolean getHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public String getTopicListeners() {
return topicListeners;
}
public void setTopicListeners(String topicListeners) {
this.topicListeners = topicListeners;
}
}
| Added a little piece of logging.
| ontopia/src/java/net/ontopia/topicmaps/impl/rdbms/RDBMSSingleTopicMapSource.java | Added a little piece of logging. | <ide><path>ntopia/src/java/net/ontopia/topicmaps/impl/rdbms/RDBMSSingleTopicMapSource.java
<ide>
<ide> this.reference = ref;
<ide> } else {
<add> log.info("Could not create reference for single RDBMS source " +
<add> id + " because no topic map found");
<ide> this.reference = null;
<ide> }
<ide> |
|
Java | apache-2.0 | 5ac683e6568d4cdf8967d6f5d3d426a01efa3cd7 | 0 | WilliamZapata/alluxio,yuluo-ding/alluxio,bf8086/alluxio,yuluo-ding/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,jswudi/alluxio,ChangerYoung/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,riversand963/alluxio,maboelhassan/alluxio,maobaolong/alluxio,apc999/alluxio,maboelhassan/alluxio,jsimsa/alluxio,wwjiang007/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,ShailShah/alluxio,maobaolong/alluxio,yuluo-ding/alluxio,bf8086/alluxio,Reidddddd/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,Alluxio/alluxio,jswudi/alluxio,apc999/alluxio,madanadit/alluxio,yuluo-ding/alluxio,maboelhassan/alluxio,madanadit/alluxio,maobaolong/alluxio,riversand963/alluxio,riversand963/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,madanadit/alluxio,apc999/alluxio,maobaolong/alluxio,uronce-cc/alluxio,Alluxio/alluxio,Alluxio/alluxio,wwjiang007/alluxio,Alluxio/alluxio,maboelhassan/alluxio,maobaolong/alluxio,Alluxio/alluxio,calvinjia/tachyon,uronce-cc/alluxio,jsimsa/alluxio,Reidddddd/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,jswudi/alluxio,calvinjia/tachyon,maboelhassan/alluxio,maboelhassan/alluxio,WilliamZapata/alluxio,aaudiber/alluxio,PasaLab/tachyon,aaudiber/alluxio,maobaolong/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,ShailShah/alluxio,madanadit/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,jsimsa/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,Reidddddd/alluxio,jsimsa/alluxio,uronce-cc/alluxio,aaudiber/alluxio,yuluo-ding/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,calvinjia/tachyon,uronce-cc/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,jswudi/alluxio,Alluxio/alluxio,calvinjia/tachyon,apc999/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,ShailShah/alluxio,uronce-cc/alluxio,Reidddddd/alluxio,jswudi/alluxio,madanadit/alluxio,jsimsa/alluxio,riversand963/alluxio,wwjiang007/alluxio,jsimsa/alluxio,riversand963/alluxio,bf8086/alluxio,bf8086/alluxio,madanadit/alluxio,ChangerYoung/alluxio,PasaLab/tachyon,yuluo-ding/alluxio,riversand963/alluxio,WilliamZapata/alluxio,Reidddddd/mo-alluxio,maobaolong/alluxio,ShailShah/alluxio,apc999/alluxio,PasaLab/tachyon,uronce-cc/alluxio,calvinjia/tachyon,bf8086/alluxio,maobaolong/alluxio,bf8086/alluxio,aaudiber/alluxio,ChangerYoung/alluxio,ShailShah/alluxio,Reidddddd/mo-alluxio,bf8086/alluxio,ShailShah/alluxio,aaudiber/alluxio,bf8086/alluxio,PasaLab/tachyon,wwjiang007/alluxio,PasaLab/tachyon,calvinjia/tachyon,Reidddddd/mo-alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,apc999/alluxio | /*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.client;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Closer;
import tachyon.Constants;
import tachyon.TachyonURI;
import tachyon.conf.TachyonConf;
import tachyon.thrift.ClientBlockInfo;
import tachyon.thrift.ClientFileInfo;
import tachyon.thrift.NetAddress;
import tachyon.underfs.UnderFileSystem;
/**
* Tachyon File.
*/
public class TachyonFile implements Comparable<TachyonFile> {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
final TachyonFS mTachyonFS;
final int mFileId;
private Object mUFSConf = null;
private final TachyonConf mTachyonConf;
/**
* A Tachyon File handler, based on file id
*
* @param tfs the Tachyon file system client handler
* @param fid the file id
* @param tachyonConf the TachyonConf for this file.
*/
TachyonFile(TachyonFS tfs, int fid, TachyonConf tachyonConf) {
mTachyonFS = tfs;
mFileId = fid;
mTachyonConf = tachyonConf;
}
private ClientFileInfo getCachedFileStatus() throws IOException {
return mTachyonFS.getFileStatus(mFileId, true);
}
private ClientFileInfo getUnCachedFileStatus() throws IOException {
return mTachyonFS.getFileStatus(mFileId, false);
}
@Override
public int compareTo(TachyonFile o) {
if (mFileId == o.mFileId) {
return 0;
}
return mFileId < o.mFileId ? -1 : 1;
}
@Override
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof TachyonFile)) {
return compareTo((TachyonFile) obj) == 0;
}
return false;
}
/**
* Return the id of a block in the file, specified by blockIndex
*
* @param blockIndex the index of the block in this file
* @return the block id
* @throws IOException
*/
public long getBlockId(int blockIndex) throws IOException {
return mTachyonFS.getBlockId(mFileId, blockIndex);
}
/**
* Return the block size of this file
*
* @return the block size in bytes
* @throws IOException
*/
public long getBlockSizeByte() throws IOException {
return getCachedFileStatus().getBlockSizeByte();
}
/**
* Get a ClientBlockInfo by the file id and block index
*
* @param blockIndex The index of the block in the file.
* @return the ClientBlockInfo of the specified block
* @throws IOException
*/
public synchronized ClientBlockInfo getClientBlockInfo(int blockIndex) throws IOException {
return mTachyonFS.getClientBlockInfo(getBlockId(blockIndex));
}
/**
* Return the creation time of this file
*
* @return the creation time, in milliseconds
* @throws IOException
*/
public long getCreationTimeMs() throws IOException {
return getCachedFileStatus().getCreationTimeMs();
}
public int getDiskReplication() {
// TODO Implement it.
return 3;
}
/**
* Return the {@code InStream} of this file based on the specified read type. If it has no block,
* return an {@code EmptyBlockInStream}; if it has only one block, return a {@code BlockInStream}
* of the block; otherwise return a {@code FileInStream}.
*
* @param readType the InStream's read type
* @return the InStream
* @throws IOException
*/
public InStream getInStream(ReadType readType) throws IOException {
if (readType == null) {
throw new IOException("ReadType can not be null.");
}
if (!isComplete()) {
throw new IOException("The file " + this + " is not complete.");
}
if (isDirectory()) {
throw new IOException("Cannot open a directory for reading.");
}
ClientFileInfo fileStatus = getUnCachedFileStatus();
List<Long> blocks = fileStatus.getBlockIds();
if (blocks.size() == 0) {
return new EmptyBlockInStream(this, readType, mTachyonConf);
}
if (blocks.size() == 1) {
return BlockInStream.get(this, readType, 0, mUFSConf, mTachyonConf);
}
return new FileInStream(this, readType, mUFSConf, mTachyonConf);
}
/**
* Returns the local filename for the block if that file exists on the local file system. This is
* an alpha power-api feature for applications that want short-circuit-read files directly. There
* is no guarantee that the file still exists after this call returns, as Tachyon may evict blocks
* from memory at any time.
*
* @param blockIndex The index of the block in the file.
* @return filename on local file system or null if file not present on local file system.
* @throws IOException
*/
public String getLocalFilename(int blockIndex) throws IOException {
ClientBlockInfo blockInfo = getClientBlockInfo(blockIndex);
long blockId = blockInfo.getBlockId();
int blockLockId = mTachyonFS.getBlockLockId();
String filename = mTachyonFS.lockBlock(blockId, blockLockId);
if (filename != null) {
mTachyonFS.unlockBlock(blockId, blockLockId);
}
return filename;
}
/**
* Return the net address of all the location hosts
*
* @return the list of those net address, in String
* @throws IOException
*/
public List<String> getLocationHosts() throws IOException {
List<String> ret = new ArrayList<String>();
if (getNumberOfBlocks() > 0) {
List<NetAddress> locations = getClientBlockInfo(0).getLocations();
if (locations != null) {
for (NetAddress location : locations) {
ret.add(location.mHost);
}
}
}
return ret;
}
/**
* Return the number of blocks the file has.
*
* @return the number of blocks
* @throws IOException
*/
public int getNumberOfBlocks() throws IOException {
return getUnCachedFileStatus().getBlockIds().size();
}
/**
* Return the {@code OutStream} of this file, use the specified write type. Always return a
* {@code FileOutStream}.
*
* @param writeType the OutStream's write type
* @return the OutStream
* @throws IOException
*/
public OutStream getOutStream(WriteType writeType) throws IOException {
if (isComplete()) {
throw new IOException("Overriding after completion not supported.");
}
if (writeType == null) {
throw new IOException("WriteType can not be null.");
}
return new FileOutStream(this, writeType, mUFSConf, mTachyonConf);
}
/**
* Return the path of this file in the Tachyon file system
*
* @return the path
* @throws IOException
*/
public String getPath() throws IOException {
return getUnCachedFileStatus().getPath();
}
/**
* To get the configuration object for UnderFileSystem.
*
* @return configuration object used for concrete ufs instance
*/
public Object getUFSConf() {
return mUFSConf;
}
/**
* Return the under filesystem path in the under file system of this file
*
* @return the under filesystem path
* @throws IOException
*/
String getUfsPath() throws IOException {
ClientFileInfo info = getCachedFileStatus();
if (!info.getUfsPath().isEmpty()) {
return info.getUfsPath();
}
return getUnCachedFileStatus().getUfsPath();
}
@Override
public int hashCode() {
return mFileId;
}
/**
* Return whether this file is complete or not
*
* @return true if this file is complete, false otherwise
* @throws IOException
*/
public boolean isComplete() throws IOException {
return getCachedFileStatus().isComplete || getUnCachedFileStatus().isComplete;
}
/**
* @return true if this is a directory, false otherwise
* @throws IOException
*/
public boolean isDirectory() throws IOException {
return getCachedFileStatus().isFolder;
}
/**
* @return true if this is a file, false otherwise
* @throws IOException
*/
public boolean isFile() throws IOException {
return !isDirectory();
}
/**
* Return whether the file is in memory or not. Note that a file may be partly in memory. This
* value is true only if the file is fully in memory.
*
* @return true if the file is fully in memory, false otherwise
* @throws IOException
*/
public boolean isInMemory() throws IOException {
return getUnCachedFileStatus().getInMemoryPercentage() == 100;
}
/**
* @return the file size in bytes
* @throws IOException
*/
public long length() throws IOException {
return getUnCachedFileStatus().getLength();
}
/**
* @return true if this file is pinned, false otherwise
* @throws IOException
*/
public boolean needPin() throws IOException {
return getUnCachedFileStatus().isPinned;
}
/**
* Promote block back to top layer after access
*
* @param blockIndex the index of the block
* @return true if success, false otherwise
* @throws IOException
*/
public boolean promoteBlock(int blockIndex) throws IOException {
ClientBlockInfo blockInfo = getClientBlockInfo(blockIndex);
return mTachyonFS.promoteBlock(blockInfo.getBlockId());
}
/**
* Advanced API.
*
* Return a TachyonByteBuffer of the block specified by the blockIndex
*
* @param blockIndex The block index of the current file to read.
* @return TachyonByteBuffer containing the block.
* @throws IOException
*/
public TachyonByteBuffer readByteBuffer(int blockIndex) throws IOException {
if (!isComplete()) {
return null;
}
// TODO allow user to disable local read for this advanced API
TachyonByteBuffer ret = readLocalByteBuffer(blockIndex);
if (ret == null) {
// TODO Make it local cache if the OpType is try cache.
ret = readRemoteByteBuffer(getClientBlockInfo(blockIndex));
}
return ret;
}
/**
* Get the the whole block.
*
* @param blockIndex The block index of the current file to read.
* @return TachyonByteBuffer containing the block.
* @throws IOException
*/
TachyonByteBuffer readLocalByteBuffer(int blockIndex) throws IOException {
return readLocalByteBuffer(blockIndex, 0, -1);
}
/**
* Read local block return a TachyonByteBuffer
*
* @param blockIndex The id of the block.
* @param offset The start position to read.
* @param len The length to read. -1 represents read the whole block.
* @return <code>TachyonByteBuffer</code> containing the block.
* @throws IOException
*/
private TachyonByteBuffer readLocalByteBuffer(int blockIndex, long offset, long len)
throws IOException {
if (offset < 0) {
throw new IOException("Offset can not be negative: " + offset);
}
if (len < 0 && len != -1) {
throw new IOException("Length can not be negative except -1: " + len);
}
ClientBlockInfo info = getClientBlockInfo(blockIndex);
long blockId = info.blockId;
int blockLockId = mTachyonFS.getBlockLockId();
String localFileName = mTachyonFS.lockBlock(blockId, blockLockId);
if (localFileName != null) {
Closer closer = Closer.create();
try {
RandomAccessFile localFile = closer.register(new RandomAccessFile(localFileName, "r"));
long fileLength = localFile.length();
String error = null;
if (offset > fileLength) {
error = String.format("Offset(%d) is larger than file length(%d)", offset, fileLength);
}
if (error == null && len != -1 && offset + len > fileLength) {
error =
String.format("Offset(%d) plus length(%d) is larger than file length(%d)", offset,
len, fileLength);
}
if (error != null) {
throw new IOException(error);
}
if (len == -1) {
len = fileLength - offset;
}
FileChannel localFileChannel = closer.register(localFile.getChannel());
final ByteBuffer buf = localFileChannel.map(FileChannel.MapMode.READ_ONLY, offset, len);
mTachyonFS.accessLocalBlock(blockId);
return new TachyonByteBuffer(mTachyonFS, buf, blockId, blockLockId);
} catch (FileNotFoundException e) {
LOG.info(localFileName + " is not on local disk.");
} catch (IOException e) {
LOG.warn("Failed to read local file " + localFileName + " because:", e);
} finally {
closer.close();
}
}
mTachyonFS.unlockBlock(blockId, blockLockId);
return null;
}
/**
* Get the the whole block from remote workers.
*
* @param blockInfo The blockInfo of the block to read.
* @return TachyonByteBuffer containing the block.
* @throws IOException if the underlying stream throws IOException during close().
*/
TachyonByteBuffer readRemoteByteBuffer(ClientBlockInfo blockInfo) throws IOException {
// Create a dummy RemoteBlockInstream object.
RemoteBlockInStream dummyStream = RemoteBlockInStream.getDummyStream();
// Using the dummy stream to read remote buffer.
ByteBuffer inBuf = dummyStream.readRemoteByteBuffer(mTachyonFS, blockInfo, 0,
blockInfo.length, mTachyonConf);
// Close the stream object.
dummyStream.close();
if (inBuf == null) {
return null;
}
// Copy data in network buffer into client buffer.
ByteBuffer outBuf = ByteBuffer.allocate((int) inBuf.capacity());
outBuf.put(inBuf);
return new TachyonByteBuffer(mTachyonFS, outBuf, blockInfo.blockId, -1);
}
// TODO remove this method. do streaming cache. This is not a right API.
public boolean recache() throws IOException {
int numberOfBlocks = getNumberOfBlocks();
if (numberOfBlocks == 0) {
return true;
}
boolean succeed = true;
for (int k = 0; k < numberOfBlocks; k ++) {
succeed &= recache(k);
}
return succeed;
}
/**
* Re-cache the block into memory
*
* @param blockIndex The block index of the current file.
* @return true if succeed, false otherwise
* @throws IOException
*/
boolean recache(int blockIndex) throws IOException {
String path = getUfsPath();
UnderFileSystem underFsClient = UnderFileSystem.get(path, mTachyonConf);
InputStream inputStream = null;
BlockOutStream bos = null;
try {
inputStream = underFsClient.open(path);
long length = getBlockSizeByte();
long offset = blockIndex * length;
inputStream.skip(offset);
int bufferBytes =
(int) mTachyonConf.getBytes(Constants.USER_FILE_BUFFER_BYTES, Constants.MB);
byte[] buffer = new byte[bufferBytes];
bos = BlockOutStream.get(this, WriteType.TRY_CACHE, blockIndex, mTachyonConf);
int limit;
while (length > 0 && ((limit = inputStream.read(buffer)) >= 0)) {
if (limit != 0) {
if (length >= limit) {
bos.write(buffer, 0, limit);
length -= limit;
} else {
bos.write(buffer, 0, (int) length);
length = 0;
}
}
}
bos.close();
} catch (IOException e) {
LOG.warn(e.getMessage(), e);
if (bos != null) {
bos.cancel();
}
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return true;
}
/**
* Rename this file
*
* @param path the new name
* @return true if succeed, false otherwise
* @throws IOException
*/
public boolean rename(TachyonURI path) throws IOException {
return mTachyonFS.rename(mFileId, path);
}
/**
* To set the configuration object for UnderFileSystem. The conf object is understood by the
* concrete underfs' implementation.
*
* @param conf The configuration object accepted by ufs.
*/
public void setUFSConf(Object conf) {
mUFSConf = conf;
}
@Override
public String toString() {
try {
return getPath();
} catch (IOException e) {
throw new RuntimeException("File does not exist anymore: " + mFileId);
}
}
}
| clients/unshaded/src/main/java/tachyon/client/TachyonFile.java | /*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.client;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Closer;
import tachyon.Constants;
import tachyon.TachyonURI;
import tachyon.conf.TachyonConf;
import tachyon.thrift.ClientBlockInfo;
import tachyon.thrift.ClientFileInfo;
import tachyon.thrift.NetAddress;
import tachyon.underfs.UnderFileSystem;
/**
* Tachyon File.
*/
public class TachyonFile implements Comparable<TachyonFile> {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
final TachyonFS mTachyonFS;
final int mFileId;
private Object mUFSConf = null;
private final TachyonConf mTachyonConf;
/**
* A Tachyon File handler, based on file id
*
* @param tfs the Tachyon file system client handler
* @param fid the file id
* @param tachyonConf the TachyonConf for this file.
*/
TachyonFile(TachyonFS tfs, int fid, TachyonConf tachyonConf) {
mTachyonFS = tfs;
mFileId = fid;
mTachyonConf = tachyonConf;
}
private ClientFileInfo getCachedFileStatus() throws IOException {
return mTachyonFS.getFileStatus(mFileId, true);
}
private ClientFileInfo getUnCachedFileStatus() throws IOException {
return mTachyonFS.getFileStatus(mFileId, false);
}
@Override
public int compareTo(TachyonFile o) {
if (mFileId == o.mFileId) {
return 0;
}
return mFileId < o.mFileId ? -1 : 1;
}
@Override
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof TachyonFile)) {
return compareTo((TachyonFile) obj) == 0;
}
return false;
}
/**
* Return the id of a block in the file, specified by blockIndex
*
* @param blockIndex the index of the block in this file
* @return the block id
* @throws IOException
*/
public long getBlockId(int blockIndex) throws IOException {
return mTachyonFS.getBlockId(mFileId, blockIndex);
}
/**
* Return the block size of this file
*
* @return the block size in bytes
* @throws IOException
*/
public long getBlockSizeByte() throws IOException {
return getCachedFileStatus().getBlockSizeByte();
}
/**
* Get a ClientBlockInfo by the file id and block index
*
* @param blockIndex The index of the block in the file.
* @return the ClientBlockInfo of the specified block
* @throws IOException
*/
public synchronized ClientBlockInfo getClientBlockInfo(int blockIndex) throws IOException {
return mTachyonFS.getClientBlockInfo(getBlockId(blockIndex));
}
/**
* Return the creation time of this file
*
* @return the creation time, in milliseconds
* @throws IOException
*/
public long getCreationTimeMs() throws IOException {
return getCachedFileStatus().getCreationTimeMs();
}
public int getDiskReplication() {
// TODO Implement it.
return 3;
}
/**
* Return the {@code InStream} of this file based on the specified read type. If it has no block,
* return an {@code EmptyBlockInStream}; if it has only one block, return a {@code BlockInStream}
* of the block; otherwise return a {@code FileInStream}.
*
* @param readType the InStream's read type
* @return the InStream
* @throws IOException
*/
public InStream getInStream(ReadType readType) throws IOException {
if (readType == null) {
throw new IOException("ReadType can not be null.");
}
if (!isComplete()) {
throw new IOException("The file " + this + " is not complete.");
}
if (isDirectory()) {
throw new IOException("Cannot open a directory for reading.");
}
ClientFileInfo fileStatus = getUnCachedFileStatus();
List<Long> blocks = fileStatus.getBlockIds();
if (blocks.size() == 0) {
return new EmptyBlockInStream(this, readType, mTachyonConf);
}
if (blocks.size() == 1) {
return BlockInStream.get(this, readType, 0, mUFSConf, mTachyonConf);
}
return new FileInStream(this, readType, mUFSConf, mTachyonConf);
}
/**
* Returns the local filename for the block if that file exists on the local file system. This is
* an alpha power-api feature for applications that want short-circuit-read files directly. There
* is no guarantee that the file still exists after this call returns, as Tachyon may evict blocks
* from memory at any time.
*
* @param blockIndex The index of the block in the file.
* @return filename on local file system or null if file not present on local file system.
* @throws IOException
*/
public String getLocalFilename(int blockIndex) throws IOException {
ClientBlockInfo blockInfo = getClientBlockInfo(blockIndex);
long blockId = blockInfo.getBlockId();
int blockLockId = mTachyonFS.getBlockLockId();
String filename = mTachyonFS.lockBlock(blockId, blockLockId);
if (filename != null) {
mTachyonFS.unlockBlock(blockId, blockLockId);
}
return filename;
}
/**
* Return the net address of all the location hosts
*
* @return the list of those net address, in String
* @throws IOException
*/
public List<String> getLocationHosts() throws IOException {
List<String> ret = new ArrayList<String>();
if (getNumberOfBlocks() > 0) {
List<NetAddress> locations = getClientBlockInfo(0).getLocations();
if (locations != null) {
for (NetAddress location : locations) {
ret.add(location.mHost);
}
}
}
return ret;
}
/**
* Return the number of blocks the file has.
*
* @return the number of blocks
* @throws IOException
*/
public int getNumberOfBlocks() throws IOException {
return getUnCachedFileStatus().getBlockIds().size();
}
/**
* Return the {@code OutStream} of this file, use the specified write type. Always return a
* {@code FileOutStream}.
*
* @param writeType the OutStream's write type
* @return the OutStream
* @throws IOException
*/
public OutStream getOutStream(WriteType writeType) throws IOException {
if (isComplete()) {
throw new IOException("Overriding after completion not supported.");
}
if (writeType == null) {
throw new IOException("WriteType can not be null.");
}
return new FileOutStream(this, writeType, mUFSConf, mTachyonConf);
}
/**
* Return the path of this file in the Tachyon file system
*
* @return the path
* @throws IOException
*/
public String getPath() throws IOException {
return getUnCachedFileStatus().getPath();
}
/**
* To get the configuration object for UnderFileSystem.
*
* @return configuration object used for concrete ufs instance
*/
public Object getUFSConf() {
return mUFSConf;
}
/**
* Return the under filesystem path in the under file system of this file
*
* @return the under filesystem path
* @throws IOException
*/
String getUfsPath() throws IOException {
ClientFileInfo info = getCachedFileStatus();
if (!info.getUfsPath().isEmpty()) {
return info.getUfsPath();
}
return getUnCachedFileStatus().getUfsPath();
}
@Override
public int hashCode() {
return mFileId;
}
/**
* Return whether this file is complete or not
*
* @return true if this file is complete, false otherwise
* @throws IOException
*/
public boolean isComplete() throws IOException {
return getCachedFileStatus().isComplete || getUnCachedFileStatus().isComplete;
}
/**
* @return true if this is a directory, false otherwise
* @throws IOException
*/
public boolean isDirectory() throws IOException {
return getCachedFileStatus().isFolder;
}
/**
* @return true if this is a file, false otherwise
* @throws IOException
*/
public boolean isFile() throws IOException {
return !isDirectory();
}
/**
* Return whether the file is in memory or not. Note that a file may be partly in memory. This
* value is true only if the file is fully in memory.
*
* @return true if the file is fully in memory, false otherwise
* @throws IOException
*/
public boolean isInMemory() throws IOException {
return getUnCachedFileStatus().getInMemoryPercentage() == 100;
}
/**
* @return the file size in bytes
* @throws IOException
*/
public long length() throws IOException {
return getUnCachedFileStatus().getLength();
}
/**
* @return true if this file is pinned, false otherwise
* @throws IOException
*/
public boolean needPin() throws IOException {
return getUnCachedFileStatus().isPinned;
}
/**
* Promote block back to top layer after access
*
* @param blockIndex the index of the block
* @return true if success, false otherwise
* @throws IOException
*/
public boolean promoteBlock(int blockIndex) throws IOException {
ClientBlockInfo blockInfo = getClientBlockInfo(blockIndex);
return mTachyonFS.promoteBlock(blockInfo.getBlockId());
}
/**
* Advanced API.
*
* Return a TachyonByteBuffer of the block specified by the blockIndex
*
* @param blockIndex The block index of the current file to read.
* @return TachyonByteBuffer containing the block.
* @throws IOException
*/
public TachyonByteBuffer readByteBuffer(int blockIndex) throws IOException {
if (!isComplete()) {
return null;
}
// TODO allow user to disable local read for this advanced API
TachyonByteBuffer ret = readLocalByteBuffer(blockIndex);
if (ret == null) {
// TODO Make it local cache if the OpType is try cache.
ret = readRemoteByteBuffer(getClientBlockInfo(blockIndex));
}
return ret;
}
/**
* Get the the whole block.
*
* @param blockIndex The block index of the current file to read.
* @return TachyonByteBuffer containing the block.
* @throws IOException
*/
TachyonByteBuffer readLocalByteBuffer(int blockIndex) throws IOException {
return readLocalByteBuffer(blockIndex, 0, -1);
}
/**
* Read local block return a TachyonByteBuffer
*
* @param blockIndex The id of the block.
* @param offset The start position to read.
* @param len The length to read. -1 represents read the whole block.
* @return <code>TachyonByteBuffer</code> containing the block.
* @throws IOException
*/
private TachyonByteBuffer readLocalByteBuffer(int blockIndex, long offset, long len)
throws IOException {
if (offset < 0) {
throw new IOException("Offset can not be negative: " + offset);
}
if (len < 0 && len != -1) {
throw new IOException("Length can not be negative except -1: " + len);
}
ClientBlockInfo info = getClientBlockInfo(blockIndex);
long blockId = info.blockId;
int blockLockId = mTachyonFS.getBlockLockId();
String localFileName = mTachyonFS.lockBlock(blockId, blockLockId);
if (localFileName != null) {
Closer closer = Closer.create();
try {
RandomAccessFile localFile = closer.register(new RandomAccessFile(localFileName, "r"));
long fileLength = localFile.length();
String error = null;
if (offset > fileLength) {
error = String.format("Offset(%d) is larger than file length(%d)", offset, fileLength);
}
if (error == null && len != -1 && offset + len > fileLength) {
error =
String.format("Offset(%d) plus length(%d) is larger than file length(%d)", offset,
len, fileLength);
}
if (error != null) {
throw new IOException(error);
}
if (len == -1) {
len = fileLength - offset;
}
FileChannel localFileChannel = closer.register(localFile.getChannel());
final ByteBuffer buf = localFileChannel.map(FileChannel.MapMode.READ_ONLY, offset, len);
mTachyonFS.accessLocalBlock(blockId);
return new TachyonByteBuffer(mTachyonFS, buf, blockId, blockLockId);
} catch (FileNotFoundException e) {
LOG.info(localFileName + " is not on local disk.");
} catch (IOException e) {
LOG.warn("Failed to read local file " + localFileName + " because:", e);
} finally {
closer.close();
}
}
mTachyonFS.unlockBlock(blockId, blockLockId);
return null;
}
/**
* Get the the whole block from remote workers.
*
* @param blockInfo The blockInfo of the block to read.
* @return TachyonByteBuffer containing the block.
* @throws IOException if the underlying stream throws IOException during close().
*/
TachyonByteBuffer readRemoteByteBuffer(ClientBlockInfo blockInfo) throws IOException {
// Create a dummy RemoteBlockInstream object.
RemoteBlockInStream dummyStream = RemoteBlockInStream.getDummyStream();
// Using the dummy stream to read remote buffer.
ByteBuffer inBuf = dummyStream.readRemoteByteBuffer(mTachyonFS, blockInfo, 0,
blockInfo.length, mTachyonConf);
// Copy data in network buffer into client buffer.
ByteBuffer outBuf = ByteBuffer.allocate((int) inBuf.capacity());
outBuf.put(inBuf);
// Close the stream object.
dummyStream.close();
return (outBuf == null)
? null : new TachyonByteBuffer(mTachyonFS, outBuf, blockInfo.blockId, -1);
}
// TODO remove this method. do streaming cache. This is not a right API.
public boolean recache() throws IOException {
int numberOfBlocks = getNumberOfBlocks();
if (numberOfBlocks == 0) {
return true;
}
boolean succeed = true;
for (int k = 0; k < numberOfBlocks; k ++) {
succeed &= recache(k);
}
return succeed;
}
/**
* Re-cache the block into memory
*
* @param blockIndex The block index of the current file.
* @return true if succeed, false otherwise
* @throws IOException
*/
boolean recache(int blockIndex) throws IOException {
String path = getUfsPath();
UnderFileSystem underFsClient = UnderFileSystem.get(path, mTachyonConf);
InputStream inputStream = null;
BlockOutStream bos = null;
try {
inputStream = underFsClient.open(path);
long length = getBlockSizeByte();
long offset = blockIndex * length;
inputStream.skip(offset);
int bufferBytes =
(int) mTachyonConf.getBytes(Constants.USER_FILE_BUFFER_BYTES, Constants.MB);
byte[] buffer = new byte[bufferBytes];
bos = BlockOutStream.get(this, WriteType.TRY_CACHE, blockIndex, mTachyonConf);
int limit;
while (length > 0 && ((limit = inputStream.read(buffer)) >= 0)) {
if (limit != 0) {
if (length >= limit) {
bos.write(buffer, 0, limit);
length -= limit;
} else {
bos.write(buffer, 0, (int) length);
length = 0;
}
}
}
bos.close();
} catch (IOException e) {
LOG.warn(e.getMessage(), e);
if (bos != null) {
bos.cancel();
}
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return true;
}
/**
* Rename this file
*
* @param path the new name
* @return true if succeed, false otherwise
* @throws IOException
*/
public boolean rename(TachyonURI path) throws IOException {
return mTachyonFS.rename(mFileId, path);
}
/**
* To set the configuration object for UnderFileSystem. The conf object is understood by the
* concrete underfs' implementation.
*
* @param conf The configuration object accepted by ufs.
*/
public void setUFSConf(Object conf) {
mUFSConf = conf;
}
@Override
public String toString() {
try {
return getPath();
} catch (IOException e) {
throw new RuntimeException("File does not exist anymore: " + mFileId);
}
}
}
| Check buffer returned from reading a dummy stream is null.
| clients/unshaded/src/main/java/tachyon/client/TachyonFile.java | Check buffer returned from reading a dummy stream is null. | <ide><path>lients/unshaded/src/main/java/tachyon/client/TachyonFile.java
<ide> // Using the dummy stream to read remote buffer.
<ide> ByteBuffer inBuf = dummyStream.readRemoteByteBuffer(mTachyonFS, blockInfo, 0,
<ide> blockInfo.length, mTachyonConf);
<add> // Close the stream object.
<add> dummyStream.close();
<add> if (inBuf == null) {
<add> return null;
<add> }
<ide> // Copy data in network buffer into client buffer.
<ide> ByteBuffer outBuf = ByteBuffer.allocate((int) inBuf.capacity());
<ide> outBuf.put(inBuf);
<del> // Close the stream object.
<del> dummyStream.close();
<del> return (outBuf == null)
<del> ? null : new TachyonByteBuffer(mTachyonFS, outBuf, blockInfo.blockId, -1);
<add> return new TachyonByteBuffer(mTachyonFS, outBuf, blockInfo.blockId, -1);
<ide> }
<ide>
<ide> // TODO remove this method. do streaming cache. This is not a right API. |
|
Java | lgpl-2.1 | 281101d9d225c92d741c45901f19708674c8b88b | 0 | cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl | package org.cytoscape.graph.render.stateful;
import static org.cytoscape.graph.render.stateful.RenderDetailFlags.*;
/*
* #%L
* Cytoscape Ding View/Presentation Impl (ding-presentation-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2013 The Cytoscape Consortium
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.awt.Font;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.cytoscape.ding.impl.work.DiscreteProgressMonitor;
import org.cytoscape.ding.impl.work.ProgressMonitor;
import org.cytoscape.ding.internal.util.MurmurHash3;
import org.cytoscape.graph.render.immed.EdgeAnchors;
import org.cytoscape.graph.render.immed.GraphGraphics;
import org.cytoscape.graph.render.stateful.GraphLOD.RenderEdges;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNode;
import org.cytoscape.util.intr.LongHash;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewSnapshot;
import org.cytoscape.view.model.SnapshotEdgeInfo;
import org.cytoscape.view.model.View;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.model.spacial.SpacialIndex2DEnumerator;
import org.cytoscape.view.presentation.customgraphics.CustomGraphicLayer;
import org.cytoscape.view.presentation.customgraphics.CyCustomGraphics;
import org.cytoscape.view.presentation.property.ArrowShapeVisualProperty;
import org.cytoscape.view.presentation.property.values.ArrowShape;
import org.cytoscape.view.presentation.property.values.Justification;
import org.cytoscape.view.presentation.property.values.Position;
import org.cytoscape.view.vizmap.VisualPropertyDependency;
/**
* This class contains a chunk of procedural code that stitches together
* several external modules in an effort to efficiently render graphs.
*/
public final class GraphRenderer {
// No constructor.
private GraphRenderer() {
}
// /**
// * Renders a graph.
// * @param netView the network view; nodes in this graph must correspond to
// * objKeys in nodePositions (the SpacialIndex2D parameter) and vice versa.
// * @param nodePositions defines the positions and extents of nodes in graph;
// * each entry (objKey) in this structure must correspond to a node in graph
// * (the CyNetwork parameter) and vice versa; the order in which nodes are
// * rendered is defined by a non-reversed overlap query on this structure.
// * @param lod defines the different levels of detail; an appropriate level
// * of detail is chosen based on the results of method calls on this
// * object.
// * @param nodeDetails defines details of nodes such as colors, node border
// * thickness, and shape; the node arguments passed to methods on this
// * object will be nodes in the graph parameter.
// * @param edgeDetails defines details of edges such as colors, thickness,
// * and arrow type; the edge arguments passed to methods on this
// * object will be edges in the graph parameter.
// * @param nodeBuff this is a computational helper that is required in the
// * implementation of this method; when this method returns, nodeBuff is
// * in a state such that an edge in graph has been rendered by this method
// * if and only if it touches at least one node in this nodeBuff set;
// * no guarantee made regarding edgeless nodes.
// * @param grafx the graphics context that is to render this graph.
// * @param bgPaint the background paint to use when calling grafx.clear().
// * @param xCenter the xCenter parameter to use when calling grafx.clear().
// * @param yCenter the yCenter parameter to use when calling grafx.clear().
// * @param scaleFactor the scaleFactor parameter to use when calling
// * grafx.clear().
// * @param dependencies
// * @return bits representing the level of detail that was rendered; the
// * return value is a bitwise-or'ed value of the LOD_* constants.
// */
// public final static void renderGraph(final CyNetworkViewSnapshot netView,
// final RenderDetailFlags flags,
// final NodeDetails nodeDetails,
// final EdgeDetails edgeDetails,
// final GraphGraphics grafx,
// final Set<VisualPropertyDependency<?>> dependencies) {
//
//// RenderDetailFlags flags = RenderDetailFlags.create(netView, grafx.getTransform(), lod, edgeDetails);
//
// if (flags.renderEdges() >= 0) {
// renderEdges(grafx, netView, flags, nodeDetails, edgeDetails);
// }
// renderNodes(grafx, netView, flags, nodeDetails, edgeDetails, dependencies);
// }
public static void renderEdges(ProgressMonitor pm, GraphGraphics grafx, CyNetworkViewSnapshot netView,
RenderDetailFlags flags, NodeDetails nodeDetails, EdgeDetails edgeDetails) {
// Render the edges first. No edge shall be rendered twice. Render edge labels.
// A label is not necessarily on top of every edge; it is only on top of the edge it belongs to.
if(flags.renderEdges() == RenderEdges.NONE) {
return;
}
final float[] floatBuff1 = new float[4];
final float[] floatBuff2 = new float[4];
final float[] floatBuff3 = new float[2];
final float[] floatBuff4 = new float[2];
final float[] floatBuff5 = new float[8];
final double[] doubleBuff1 = new double[4];
final double[] doubleBuff2 = new double[2];
final GeneralPath path2d = new GeneralPath();
final LongHash nodeBuff = new LongHash();
final SpacialIndex2DEnumerator<Long> nodeHits;
Rectangle2D.Float area = grafx.getTransform().getNetworkVisibleAreaNodeCoords();
if (flags.renderEdges() == RenderEdges.ALL)
// We want to render edges in the same order (back to front) that
// we would use to render just edges on visible nodes; this is assuming
// that our spacial index has the subquery order-preserving property.
nodeHits = netView.getSpacialIndex2D().queryAll();
else
nodeHits = netView.getSpacialIndex2D().queryOverlap(area.x, area.y, area.x + area.width, area.y + area.height); // MKTODO why are we querying twice?
if (flags.not(LOD_HIGH_DETAIL)) { // Low detail.
ProgressMonitor[] subPms = pm.split(1,0); // no labels at all, still need labelPm for debug panel
ProgressMonitor shapePm = subPms[0];
ProgressMonitor labelPm = subPms[1];
shapePm.start("Line");
DiscreteProgressMonitor shapeDpm = shapePm.toDiscrete(nodeHits.size());
while (nodeHits.hasNext()) {
if(pm.isCancelled()) {
return;
}
final long nodeSuid = nodeHits.nextExtents(floatBuff1);
// Casting to double and then back we could achieve better accuracy
// at the expense of performance.
final float nodeX = (floatBuff1[0] + floatBuff1[2]) / 2;
final float nodeY = (floatBuff1[1] + floatBuff1[3]) / 2;
Iterable<View<CyEdge>> touchingEdges = netView.getAdjacentEdgeIterable(nodeSuid);
for ( View<CyEdge> edge : touchingEdges ) {
if (!edgeDetails.isVisible(edge))
continue;
SnapshotEdgeInfo edgeInfo = netView.getEdgeInfo(edge);
final long otherNode = nodeSuid ^ edgeInfo.getSourceViewSUID() ^ edgeInfo.getTargetViewSUID();
if (nodeBuff.get(otherNode) < 0) { // Has not yet been rendered.
netView.getSpacialIndex2D().get(otherNode, floatBuff2);
grafx.drawEdgeLow(nodeX, nodeY,
// Again, casting issue - tradeoff between
// accuracy and performance.
(floatBuff2[0] + floatBuff2[2]) / 2,
(floatBuff2[1] + floatBuff2[3]) / 2,
edgeDetails.getColorLowDetail(netView, edge));
}
}
nodeBuff.put(nodeSuid);
shapeDpm.increment();
}
shapePm.done();
labelPm.emptyTask("Label");
} else { // High detail.
ProgressMonitor[] subPms = pm.split(1,1); // labels usually take longer
ProgressMonitor shapePm = subPms[0];
ProgressMonitor labelPm = subPms[1];
DiscreteProgressMonitor shapeDpm = shapePm.toDiscrete(nodeHits.size());
DiscreteProgressMonitor labelDpm = labelPm.toDiscrete(nodeHits.size());
byte[] haystackDataBuff = new byte[16];
while (nodeHits.hasNext()) {
if(pm.isCancelled())
return;
final long nodeSuid = nodeHits.nextExtents(floatBuff1);
final View<CyNode> node = netView.getNodeView(nodeSuid);
final byte nodeShape = nodeDetails.getShape(node);
Iterable<View<CyEdge>> touchingEdges = netView.getAdjacentEdgeIterable(node);
for (View<CyEdge> edge : touchingEdges) {
if(pm.isCancelled()) {
return;
}
if (!edgeDetails.isVisible(edge))
continue;
SnapshotEdgeInfo edgeInfo = netView.getEdgeInfo(edge);
long edgeSuid = edgeInfo.getSUID();
var sourceViewSUID = edgeInfo.getSourceViewSUID();
var targetViewSUID = edgeInfo.getTargetViewSUID();
final long otherNode = nodeSuid ^ sourceViewSUID ^ targetViewSUID;
final View<CyNode> otherCyNode = netView.getNodeView(otherNode);
boolean haystack = edgeDetails.isHaystack(edge);
if (nodeBuff.get(otherNode) < 0) { // Has not yet been rendered.
shapePm.start("Line");
if (!netView.getSpacialIndex2D().get(otherNode, floatBuff2))
continue;
// throw new IllegalStateException("nodePositions not recognizing node that exists in graph: "+otherCyNode.toString());
final byte otherNodeShape = nodeDetails.getShape(otherCyNode);
final byte srcShape;
final byte trgShape;
final float[] srcExtents;
final float[] trgExtents;
final long srcSuid;
final long trgSuid;
if (nodeSuid == sourceViewSUID) {
srcShape = nodeShape;
trgShape = otherNodeShape;
srcExtents = floatBuff1;
trgExtents = floatBuff2;
srcSuid = nodeSuid;
trgSuid = otherNode;
} else {
srcShape = otherNodeShape;
trgShape = nodeShape;
srcExtents = floatBuff2;
trgExtents = floatBuff1;
srcSuid = otherNode;
trgSuid = nodeSuid;
}
// Compute visual attributes that do not depend on LOD.
final float thickness = (float) edgeDetails.getWidth(edge);
final Stroke edgeStroke = edgeDetails.getStroke(edge);
final Paint segPaint = edgeDetails.getPaint(edge);
// Compute arrows.
final ArrowShape srcArrow;
final ArrowShape trgArrow;
final float srcArrowSize;
final float trgArrowSize;
final Paint srcArrowPaint;
final Paint trgArrowPaint;
if (flags.not(LOD_EDGE_ARROWS) || haystack) { // Not rendering arrows.
trgArrow = srcArrow = ArrowShapeVisualProperty.NONE;
trgArrowSize = srcArrowSize = 0.0f;
trgArrowPaint = srcArrowPaint = null;
} else { // Rendering edge arrows.
srcArrow = edgeDetails.getSourceArrowShape(edge);
trgArrow = edgeDetails.getTargetArrowShape(edge);
srcArrowSize = ((srcArrow == ArrowShapeVisualProperty.NONE) ? 0.0f : edgeDetails.getSourceArrowSize(edge));
trgArrowSize = ((trgArrow == ArrowShapeVisualProperty.NONE) ? 0.0f : edgeDetails.getTargetArrowSize(edge));
srcArrowPaint = ((srcArrow == ArrowShapeVisualProperty.NONE) ? null : edgeDetails.getSourceArrowPaint(edge));
trgArrowPaint = ((trgArrow == ArrowShapeVisualProperty.NONE) ? null : edgeDetails.getTargetArrowPaint(edge));
}
// Compute the anchors to use when rendering edge.
final EdgeAnchors anchors = flags.not(LOD_EDGE_ANCHORS) ? null : edgeDetails.getAnchors(netView, edge);
if(haystack) {
float radiusModifier = edgeDetails.getHaystackRadius(edge);
if (!computeEdgeEndpointsHaystack(srcExtents, trgExtents, floatBuff3, floatBuff4,
srcSuid, trgSuid, edgeSuid, haystackDataBuff, radiusModifier))
continue;
}
else {
if (!computeEdgeEndpoints(srcExtents, srcShape, srcArrow,
srcArrowSize, anchors, trgExtents, trgShape,
trgArrow, trgArrowSize, floatBuff3, floatBuff4))
continue;
}
final float srcXAdj = floatBuff3[0];
final float srcYAdj = floatBuff3[1];
final float trgXAdj = floatBuff4[0];
final float trgYAdj = floatBuff4[1];
grafx.drawEdgeFull(srcArrow, srcArrowSize, srcArrowPaint, trgArrow,
trgArrowSize, trgArrowPaint, srcXAdj, srcYAdj,
anchors, trgXAdj, trgYAdj, thickness, edgeStroke, segPaint);
// Take care of edge anchor rendering.
if (anchors != null) {
for (int k = 0; k < anchors.numAnchors(); k++) {
final float anchorSize;
if ((anchorSize = edgeDetails.getAnchorSize(edge, k)) > 0.0f) {
anchors.getAnchor(k, floatBuff4);
grafx.drawNodeFull(GraphGraphics.SHAPE_RECTANGLE,
(float) (floatBuff4[0] - (anchorSize / 2.0d)),
(float) (floatBuff4[1] - (anchorSize / 2.0d)),
(float) (floatBuff4[0] + (anchorSize / 2.0d)),
(float) (floatBuff4[1] + (anchorSize / 2.0d)),
edgeDetails.getAnchorPaint(edge, k), 0.0f, null, null);
}
}
}
shapePm.done();
labelPm.start("Label");
// Take care of label rendering.
if (flags.has(LOD_EDGE_LABELS)) {
final int labelCount = edgeDetails.getLabelCount(edge);
for (int labelInx = 0; labelInx < labelCount; labelInx++) {
if(pm.isCancelled()) {
return;
}
final String text = edgeDetails.getLabelText(edge);
final Font font = edgeDetails.getLabelFont(edge);
final double fontScaleFactor = edgeDetails.getLabelScaleFactor(edge);
final Paint paint = edgeDetails.getLabelPaint(edge);
final Position textAnchor = edgeDetails.getLabelTextAnchor(edge);
final Position edgeAnchor = edgeDetails.getLabelEdgeAnchor(edge);
final float offsetVectorX = edgeDetails.getLabelOffsetVectorX(edge);
final float offsetVectorY = edgeDetails.getLabelOffsetVectorY(edge);
final double theta = edgeDetails.getLabelRotation(edge)*.01745329252;
final Justification justify;
if (text.indexOf('\n') >= 0)
justify = edgeDetails.getLabelJustify(edge);
else
justify = Justification.JUSTIFY_CENTER;
final double edgeAnchorPointX;
final double edgeAnchorPointY;
final double edgeLabelWidth = edgeDetails.getLabelWidth(edge);
// Note that we reuse the position enum here. West == source and East == target
// This is sort of safe since we don't provide an API for changing this
// in any case.
if (edgeAnchor == Position.WEST) { edgeAnchorPointX = srcXAdj; edgeAnchorPointY = srcYAdj;
} else if (edgeAnchor == Position.EAST) { edgeAnchorPointX = trgXAdj; edgeAnchorPointY = trgYAdj;
} else if (edgeAnchor == Position.CENTER) {
if (!GraphGraphics.getEdgePath(srcArrow, srcArrowSize, trgArrow,
trgArrowSize, srcXAdj, srcYAdj, anchors, trgXAdj, trgYAdj, path2d)) {
continue;
}
// Count the number of path segments. This count
// includes the initial SEG_MOVETO. So, for example, a
// path composed of 2 cubic curves would have a numPaths
// of 3. Note that numPaths will be at least 2 in all
// cases.
final int numPaths;
{
final PathIterator pathIter = path2d.getPathIterator(null);
int numPathsTemp = 0;
while (!pathIter.isDone()) {
numPathsTemp++; // pathIter.currentSegment().
pathIter.next();
}
numPaths = numPathsTemp;
}
// Compute "midpoint" of edge.
if ((numPaths % 2) != 0) {
final PathIterator pathIter = path2d.getPathIterator(null);
for (int i = numPaths / 2; i > 0; i--)
pathIter.next();
final int subPathType = pathIter.currentSegment(floatBuff5);
if (subPathType == PathIterator.SEG_LINETO) {
edgeAnchorPointX = floatBuff5[0];
edgeAnchorPointY = floatBuff5[1];
} else if (subPathType == PathIterator.SEG_QUADTO) {
edgeAnchorPointX = floatBuff5[2];
edgeAnchorPointY = floatBuff5[3];
} else if (subPathType == PathIterator.SEG_CUBICTO) {
edgeAnchorPointX = floatBuff5[4];
edgeAnchorPointY = floatBuff5[5];
} else
throw new IllegalStateException("got unexpected PathIterator segment type: " + subPathType);
} else { // numPaths % 2 == 0.
final PathIterator pathIter = path2d.getPathIterator(null);
for (int i = numPaths / 2; i > 0; i--) {
if (i == 1) {
final int subPathType = pathIter.currentSegment(floatBuff5);
if ((subPathType == PathIterator.SEG_MOVETO)
|| (subPathType == PathIterator.SEG_LINETO)) {
floatBuff5[6] = floatBuff5[0];
floatBuff5[7] = floatBuff5[1];
} else if (subPathType == PathIterator.SEG_QUADTO) {
floatBuff5[6] = floatBuff5[2];
floatBuff5[7] = floatBuff5[3];
} else if (subPathType == PathIterator.SEG_CUBICTO) {
floatBuff5[6] = floatBuff5[4];
floatBuff5[7] = floatBuff5[5];
} else
throw new IllegalStateException("got unexpected PathIterator segment type: " + subPathType);
}
pathIter.next();
}
final int subPathType = pathIter.currentSegment(floatBuff5);
if (subPathType == PathIterator.SEG_LINETO) {
edgeAnchorPointX = (0.5d * floatBuff5[6]) + (0.5d * floatBuff5[0]);
edgeAnchorPointY = (0.5d * floatBuff5[7]) + (0.5d * floatBuff5[1]);
} else if (subPathType == PathIterator.SEG_QUADTO) {
edgeAnchorPointX = (0.25d * floatBuff5[6]) + (0.5d * floatBuff5[0]) + (0.25d * floatBuff5[2]);
edgeAnchorPointY = (0.25d * floatBuff5[7]) + (0.5d * floatBuff5[1]) + (0.25d * floatBuff5[3]);
} else if (subPathType == PathIterator.SEG_CUBICTO) {
edgeAnchorPointX = (0.125d * floatBuff5[6]) + (0.375d * floatBuff5[0]) + (0.375d * floatBuff5[2]) + (0.125d * floatBuff5[4]);
edgeAnchorPointY = (0.125d * floatBuff5[7]) + (0.375d * floatBuff5[1]) + (0.375d * floatBuff5[3]) + (0.125d * floatBuff5[5]);
} else
throw new IllegalStateException("got unexpected PathIterator segment type: " + subPathType);
}
} else
throw new IllegalStateException("encountered an invalid EDGE_ANCHOR_* constant: " + edgeAnchor);
final MeasuredLineCreator measuredText =
new MeasuredLineCreator(text,font,
grafx.getFontRenderContextFull(),
fontScaleFactor,
flags.has(LOD_TEXT_AS_SHAPE),
edgeLabelWidth);
doubleBuff1[0] = -0.5d * measuredText.getMaxLineWidth();
doubleBuff1[1] = -0.5d * measuredText.getTotalHeight();
doubleBuff1[2] = 0.5d * measuredText.getMaxLineWidth();
doubleBuff1[3] = 0.5d * measuredText.getTotalHeight();
lemma_computeAnchor(textAnchor, doubleBuff1, doubleBuff2);
final double textXCenter = edgeAnchorPointX - doubleBuff2[0] + offsetVectorX;
final double textYCenter = edgeAnchorPointY - doubleBuff2[1] + offsetVectorY;
TextRenderingUtils.renderText(grafx, measuredText,
font, fontScaleFactor,
(float) textXCenter,
(float) textYCenter,
justify, paint, theta,
flags.has(LOD_TEXT_AS_SHAPE));
}
}
labelPm.done();
}
}
nodeBuff.put(nodeSuid);
shapeDpm.increment();
labelDpm.increment();
}
}
}
public static void renderNodes(ProgressMonitor pm, GraphGraphics grafx, CyNetworkViewSnapshot netView,
RenderDetailFlags flags, NodeDetails nodeDetails, EdgeDetails edgeDetails, Set<VisualPropertyDependency<?>> dependencies) {
// Render nodes and labels. A label is not necessarily on top of every
// node; it is only on top of the node it belongs to.
final float[] floatBuff1 = new float[4];
final double[] doubleBuff1 = new double[4];
final double[] doubleBuff2 = new double[2];
Rectangle2D.Float area = grafx.getTransform().getNetworkVisibleAreaNodeCoords();
SpacialIndex2DEnumerator<Long> nodeHits = netView.getSpacialIndex2D().queryOverlap(area.x, area.y, area.x + area.width, area.y + area.height);
if (flags.not(LOD_HIGH_DETAIL)) { // Low detail.
ProgressMonitor[] subPms = pm.split(1,0); // no labels at all, still need labelPm for debug panel
ProgressMonitor shapePm = subPms[0];
ProgressMonitor labelPm = subPms[1];
shapePm.start("Shape");
final int nodeHitCount = nodeHits.size();
DiscreteProgressMonitor shapeDpm = shapePm.toDiscrete(nodeHitCount);
for (int i = 0; i < nodeHitCount; i++) {
if(pm.isCancelled())
return;
final View<CyNode> node = netView.getNodeView( nodeHits.nextExtents(floatBuff1) );
if ((floatBuff1[0] != floatBuff1[2]) && (floatBuff1[1] != floatBuff1[3]))
grafx.drawNodeLow(floatBuff1[0], floatBuff1[1], floatBuff1[2],
floatBuff1[3], nodeDetails.getColorLowDetail(netView, node));
shapeDpm.increment();
}
shapePm.done();
labelPm.emptyTask("Label");
} else { // High detail.
ProgressMonitor[] subPms = pm.split(1,2); // labels usually take longer
ProgressMonitor shapePm = subPms[0];
ProgressMonitor labelPm = subPms[1];
DiscreteProgressMonitor shapeDpm = shapePm.toDiscrete(nodeHits.size());
DiscreteProgressMonitor labelDpm = labelPm.toDiscrete(nodeHits.size());
while (nodeHits.hasNext()) {
if(pm.isCancelled())
return;
final long node = nodeHits.nextExtents(floatBuff1);
final View<CyNode> cyNode = netView.getNodeView(node);
shapePm.start("Shape");
renderNodeHigh(netView, grafx, cyNode, floatBuff1, doubleBuff1, doubleBuff2, nodeDetails, flags, dependencies);
shapeDpm.increment();
shapePm.done();
labelPm.start("Label");
// Take care of label rendering.
if (flags.has(LOD_NODE_LABELS)) { // Potential label rendering.
final int labelCount = nodeDetails.getLabelCount(cyNode);
for (int labelInx = 0; labelInx < labelCount; labelInx++) {
final String text = nodeDetails.getLabelText(cyNode);
final Font font = nodeDetails.getLabelFont(cyNode);
final double fontScaleFactor = nodeDetails.getLabelScaleFactor(cyNode);
final Paint paint = nodeDetails.getLabelPaint(cyNode);
final Position textAnchor = nodeDetails.getLabelTextAnchor(cyNode);
final Position nodeAnchor = nodeDetails.getLabelNodeAnchor(cyNode);
final float offsetVectorX = nodeDetails.getLabelOffsetVectorX(cyNode);
final float offsetVectorY = nodeDetails.getLabelOffsetVectorY(cyNode);
final double theta = nodeDetails.getLabelRotation(cyNode)*.01745329252;
final Justification justify;
if (text.indexOf('\n') >= 0)
justify = nodeDetails.getLabelJustify(cyNode);
else
justify = Justification.JUSTIFY_CENTER;
final double nodeLabelWidth = nodeDetails.getLabelWidth(cyNode);
doubleBuff1[0] = floatBuff1[0];
doubleBuff1[1] = floatBuff1[1];
doubleBuff1[2] = floatBuff1[2];
doubleBuff1[3] = floatBuff1[3];
lemma_computeAnchor(nodeAnchor, doubleBuff1, doubleBuff2);
final double nodeAnchorPointX = doubleBuff2[0];
final double nodeAnchorPointY = doubleBuff2[1];
final MeasuredLineCreator measuredText = new MeasuredLineCreator(
text, font, grafx.getFontRenderContextFull(), fontScaleFactor,
flags.has(LOD_TEXT_AS_SHAPE), nodeLabelWidth);
doubleBuff1[0] = -0.5d * measuredText.getMaxLineWidth();
doubleBuff1[1] = -0.5d * measuredText.getTotalHeight();
doubleBuff1[2] = 0.5d * measuredText.getMaxLineWidth();
doubleBuff1[3] = 0.5d * measuredText.getTotalHeight();
lemma_computeAnchor(textAnchor, doubleBuff1, doubleBuff2);
final double textXCenter = nodeAnchorPointX - doubleBuff2[0] + offsetVectorX;
final double textYCenter = nodeAnchorPointY - doubleBuff2[1] + offsetVectorY;
TextRenderingUtils.renderText(grafx, measuredText, font,
fontScaleFactor,
(float) textXCenter,
(float) textYCenter, justify,
paint,theta,
flags.has(LOD_TEXT_AS_SHAPE));
}
}
labelDpm.increment();
labelPm.done();
}
}
}
/**
*
* @param anchor
* @param input4x An array of 4 elements: x0,y0,x1, y1 of a rectangle
* @param rtrn2x An array of 2 element. x and y coordinates of the center of the object.
*/
public final static void lemma_computeAnchor(final Position anchor, final double[] input4x,
final double[] rtrn2x) {
switch (anchor) {
case CENTER:
rtrn2x[0] = (input4x[0] + input4x[2]) / 2.0d;
rtrn2x[1] = (input4x[1] + input4x[3]) / 2.0d;
break;
case SOUTH:
rtrn2x[0] = (input4x[0] + input4x[2]) / 2.0d;
rtrn2x[1] = input4x[3];
break;
case SOUTH_EAST:
rtrn2x[0] = input4x[2];
rtrn2x[1] = input4x[3];
break;
case EAST:
rtrn2x[0] = input4x[2];
rtrn2x[1] = (input4x[1] + input4x[3]) / 2.0d;
break;
case NORTH_EAST:
rtrn2x[0] = input4x[2];
rtrn2x[1] = input4x[1];
break;
case NORTH:
rtrn2x[0] = (input4x[0] + input4x[2]) / 2.0d;
rtrn2x[1] = input4x[1];
break;
case NORTH_WEST:
rtrn2x[0] = input4x[0];
rtrn2x[1] = input4x[1];
break;
case WEST:
rtrn2x[0] = input4x[0];
rtrn2x[1] = (input4x[1] + input4x[3]) / 2.0d;
break;
case SOUTH_WEST:
rtrn2x[0] = input4x[0];
rtrn2x[1] = input4x[3];
break;
default:
throw new IllegalStateException("encoutered an invalid ANCHOR_* constant: "
+ anchor);
}
}
public final static boolean computeEdgeEndpointsHaystack(final float[] srcNodeExtents, final float[] trgNodeExtents,
final float[] rtnValSrc, final float[] rtnValTrg, long srcSuid, long trgSuid,
long edgeSuid, byte[] dataBuff, float radiusModifier) {
haystackEndpoint(srcNodeExtents, rtnValSrc, dataBuff, srcSuid, edgeSuid, radiusModifier);
haystackEndpoint(trgNodeExtents, rtnValTrg, dataBuff, trgSuid, edgeSuid, radiusModifier);
return true;
}
/**
* Computes a 'random' point around the circumference of a circle within the node.
*/
private final static void haystackEndpoint(float[] nodeExtents, float[] rtnVal,
byte[] dataBuff, long nodeSuid, long edgeSuid, float radiusModifier) {
final float xMin = nodeExtents[0];
final float yMin = nodeExtents[1];
final float xMax = nodeExtents[2];
final float yMax = nodeExtents[3];
final float centerX = (xMin + xMax) / 2.0f;
final float centerY = (yMin + yMax) / 2.0f;
final float width = xMax - xMin;
final float height = yMax - yMin;
final float radius = (Math.min(width, height) / 2.0f) * radiusModifier;
// Hash the node and edge SUIDs to a value between 0.0 and 1.0. This is done instead of
// generating a random number so that the edge endpoints stay consistent between frames.
float h1 = hashSuids(dataBuff, nodeSuid, edgeSuid, 99);
// Use the hash to get a 'random' point around the circumference
// of a circle that lies within the node boundaries.
double theta = h1 * Math.PI * 2;
double x = centerX + Math.cos(theta) * radius;
double y = centerY + Math.sin(theta) * radius;
rtnVal[0] = (float) x;
rtnVal[1] = (float) y;
}
private static void longToBytes(long l, byte[] buff, int offset) {
for (int i = offset + 7; i >= offset; i--) {
buff[i] = (byte) (l & 0xFF);
l >>= 8;
}
}
/**
* Returns a hashed value of the given suids in the range 0.0 to 1.0
*/
private static float hashSuids(byte[] dataBuff, long nodeSuid, long edgeSuid, int seed) {
longToBytes(nodeSuid, dataBuff, 0);
longToBytes(edgeSuid, dataBuff, 8);
int hash = MurmurHash3.murmurhash3_x86_32(dataBuff, 0, dataBuff.length, seed);
float r = Math.abs((float) hash / Integer.MAX_VALUE);
return r;
}
/**
* Calculates the edge endpoints given two nodes, any edge anchors, and any arrows.
*
* @param grafx The GraphGraphics being used to render everything. Used only to
* calculate the edge intersection of the node.
* @param srcNodeExtents The extents of the source node.
* @param srcNodeShape The node shape type.
* @param srcArrow The source arrow type.
* @param srcArrowSize The source arrow size.
* @param anchors an EdgeAnchors object listing any anchors for the edge, possibly null.
* @param trgNodeExtents The extends of the target node.
* @param trgNodeShape The target node type.
* @param trgArrow The target arrow type.
* @param trgArrowSize The target arrow size.
* @param rtnValSrc The array where X,Y positions of the source end of the edge are stored.
* @param rtnValTrg The array where X,Y positions of the target end of the edge are stored.
*
* @return DOCUMENT ME!
*/
public final static boolean computeEdgeEndpoints(final float[] srcNodeExtents,
final byte srcNodeShape, final ArrowShape srcArrow,
final float srcArrowSize, EdgeAnchors anchors,
final float[] trgNodeExtents,
final byte trgNodeShape, final ArrowShape trgArrow,
final float trgArrowSize,
final float[] rtnValSrc,
final float[] rtnValTrg) {
final float srcX = (float) ((((double) srcNodeExtents[0]) + srcNodeExtents[2]) / 2.0d);
final float srcY = (float) ((((double) srcNodeExtents[1]) + srcNodeExtents[3]) / 2.0d);
final float trgX = (float) ((((double) trgNodeExtents[0]) + trgNodeExtents[2]) / 2.0d);
final float trgY = (float) ((((double) trgNodeExtents[1]) + trgNodeExtents[3]) / 2.0d);
final float srcXOut;
final float srcYOut;
final float trgXOut;
final float trgYOut;
final float[] floatBuff = new float[2];
if ((anchors != null) && (anchors.numAnchors() == 0))
anchors = null;
if (anchors == null) {
srcXOut = trgX;
srcYOut = trgY;
trgXOut = srcX;
trgYOut = srcY;
} else {
anchors.getAnchor(0, floatBuff);
srcXOut = floatBuff[0];
srcYOut = floatBuff[1];
anchors.getAnchor(anchors.numAnchors() - 1, floatBuff);
trgXOut = floatBuff[0];
trgYOut = floatBuff[1];
}
calcIntersection(srcNodeShape, srcNodeExtents, srcX, srcY, srcXOut, srcYOut, floatBuff);
final float srcXAdj = floatBuff[0];
final float srcYAdj = floatBuff[1];
calcIntersection(trgNodeShape, trgNodeExtents, trgX, trgY, trgXOut, trgYOut, floatBuff);
final float trgXAdj = floatBuff[0];
final float trgYAdj = floatBuff[1];
rtnValSrc[0] = srcXAdj;
rtnValSrc[1] = srcYAdj;
rtnValTrg[0] = trgXAdj;
rtnValTrg[1] = trgYAdj;
return true;
}
private static void calcIntersection(byte nodeShape,
float[] nodeExtents, float x, float y,
float xOut, float yOut, float[] retVal) {
if ((nodeExtents[0] == nodeExtents[2]) ||
(nodeExtents[1] == nodeExtents[3])) {
retVal[0] = x;
retVal[1] = y;
} else {
if (!GraphGraphics.computeEdgeIntersection(nodeShape, nodeExtents[0],
nodeExtents[1], nodeExtents[2],
nodeExtents[3], 0.0f, xOut, yOut,
retVal)) {
final float newXOut;
final float newYOut;
final double xCenter = (((double) nodeExtents[0]) + nodeExtents[2]) / 2.0d;
final double yCenter = (((double) nodeExtents[1]) + nodeExtents[3]) / 2.0d;
final double desiredDist = Math.max(((double) nodeExtents[2])
- nodeExtents[0],
((double) nodeExtents[3])
- nodeExtents[1]);
final double dX = xOut - xCenter;
final double dY = yOut - yCenter;
final double len = Math.sqrt((dX * dX) + (dY * dY));
if (len == 0.0d) {
newXOut = (float) (xOut + desiredDist);
newYOut = yOut;
} else {
newXOut = (float) (((dX / len) * desiredDist) + xOut);
newYOut = (float) (((dY / len) * desiredDist) + yOut);
}
GraphGraphics.computeEdgeIntersection(nodeShape, nodeExtents[0],
nodeExtents[1], nodeExtents[2],
nodeExtents[3], 0.0f, newXOut,
newYOut, retVal);
}
}
}
private final static float[] s_floatTemp = new float[6];
private final static int[] s_segTypeBuff = new int[200];
private final static float[] s_floatBuff2 = new float[1200];
/**
* DOCUMENT ME!
*
* @param origPath DOCUMENT ME!
* @param rtnVal DOCUMENT ME!
*/
public final static void computeClosedPath(final PathIterator origPath, final GeneralPath rtnVal) {
synchronized (s_floatTemp) {
// First fill our buffers with the coordinates and segment types.
int segs = 0;
int offset = 0;
if ((s_segTypeBuff[segs++] = origPath.currentSegment(s_floatTemp)) != PathIterator.SEG_MOVETO)
throw new IllegalStateException("expected a SEG_MOVETO at the beginning of origPath");
for (int i = 0; i < 2; i++)
s_floatBuff2[offset++] = s_floatTemp[i];
origPath.next();
while (!origPath.isDone()) {
final int segType = origPath.currentSegment(s_floatTemp);
s_segTypeBuff[segs++] = segType;
if ((segType == PathIterator.SEG_MOVETO) || (segType == PathIterator.SEG_CLOSE))
throw new IllegalStateException("did not expect SEG_MOVETO or SEG_CLOSE");
// This is a rare case where I rely on the actual constant values
// to do a computation efficiently.
final int coordCount = segType * 2;
for (int i = 0; i < coordCount; i++)
s_floatBuff2[offset++] = s_floatTemp[i];
origPath.next();
}
rtnVal.reset();
offset = 0;
// Now add the forward path to rtnVal.
for (int i = 0; i < segs; i++) {
switch (s_segTypeBuff[i]) {
case PathIterator.SEG_MOVETO:
rtnVal.moveTo(s_floatBuff2[offset++], s_floatBuff2[offset++]);
break;
case PathIterator.SEG_LINETO:
rtnVal.lineTo(s_floatBuff2[offset++], s_floatBuff2[offset++]);
break;
case PathIterator.SEG_QUADTO:
rtnVal.quadTo(s_floatBuff2[offset++], s_floatBuff2[offset++],
s_floatBuff2[offset++], s_floatBuff2[offset++]);
break;
default: // PathIterator.SEG_CUBICTO.
rtnVal.curveTo(s_floatBuff2[offset++], s_floatBuff2[offset++],
s_floatBuff2[offset++], s_floatBuff2[offset++],
s_floatBuff2[offset++], s_floatBuff2[offset++]);
break;
}
}
// Now add the return path.
for (int i = segs - 1; i > 0; i--) {
switch (s_segTypeBuff[i]) {
case PathIterator.SEG_LINETO:
offset -= 2;
rtnVal.lineTo(s_floatBuff2[offset - 2], s_floatBuff2[offset - 1]);
break;
case PathIterator.SEG_QUADTO:
offset -= 4;
rtnVal.quadTo(s_floatBuff2[offset], s_floatBuff2[offset + 1],
s_floatBuff2[offset - 2], s_floatBuff2[offset - 1]);
break;
default: // PathIterator.SEG_CUBICTO.
offset -= 6;
rtnVal.curveTo(s_floatBuff2[offset + 2], s_floatBuff2[offset + 3],
s_floatBuff2[offset], s_floatBuff2[offset + 1],
s_floatBuff2[offset - 2], s_floatBuff2[offset - 1]);
break;
}
}
rtnVal.closePath();
}
}
static final boolean _computeEdgeIntersection(final float nodeX, final float nodeY,
final float offset, final float ptX,
final float ptY, final boolean alwaysCompute,
final float[] returnVal) {
if (offset == 0.0f) {
returnVal[0] = nodeX;
returnVal[1] = nodeY;
return true;
} else {
final double dX = ptX - nodeX;
final double dY = ptY - nodeY;
final double len = Math.sqrt((dX * dX) + (dY * dY));
if (len < offset) {
if (!alwaysCompute)
return false;
if (len == 0.0d) {
returnVal[0] = offset + nodeX;
returnVal[1] = nodeY;
return true;
}
}
returnVal[0] = (float) (((dX / len) * offset) + nodeX);
returnVal[1] = (float) (((dY / len) * offset) + nodeY);
return true;
}
}
/**
* Render node view with details, including custom graphics.
*/
@SuppressWarnings("rawtypes")
private static final void renderNodeHigh(final CyNetworkViewSnapshot netView,
final GraphGraphics grafx,
final View<CyNode> cyNode,
final float[] floatBuff1,
final double[] doubleBuff1,
final double[] doubleBuff2,
final NodeDetails nodeDetails,
final RenderDetailFlags flags,
final Set<VisualPropertyDependency<?>> dependencies) {
Shape nodeShape = null;
if ((floatBuff1[0] != floatBuff1[2]) && (floatBuff1[1] != floatBuff1[3])) {
// Compute visual attributes that do not depend on LOD.
final byte shape = nodeDetails.getShape(cyNode);
final Paint fillPaint = nodeDetails.getFillPaint(cyNode);
// Compute node border information.
final float borderWidth;
final Paint borderPaint;
Stroke borderStroke = null;
if (flags.not(LOD_NODE_BORDERS)) { // Not rendering borders.
borderWidth = 0.0f;
borderPaint = null;
} else { // Rendering node borders.
borderWidth = nodeDetails.getBorderWidth(cyNode);
borderStroke = nodeDetails.getBorderStroke(cyNode);
if (borderWidth == 0.0f)
borderPaint = null;
else
borderPaint = nodeDetails.getBorderPaint(cyNode);
}
// Draw the node.
nodeShape = grafx.drawNodeFull(shape, floatBuff1[0], floatBuff1[1], floatBuff1[2], floatBuff1[3],
fillPaint, borderWidth, borderStroke, borderPaint);
}
// Take care of custom graphic rendering.
if (flags.has(LOD_CUSTOM_GRAPHICS)) {
// draw any nested networks first
final TexturePaint nestedNetworkPaint = nodeDetails.getNestedNetworkTexturePaint(netView, cyNode);
if (nestedNetworkPaint != null) {
doubleBuff1[0] = floatBuff1[0];
doubleBuff1[1] = floatBuff1[1];
doubleBuff1[2] = floatBuff1[2];
doubleBuff1[3] = floatBuff1[3];
lemma_computeAnchor(Position.CENTER, doubleBuff1, doubleBuff2);
grafx.drawCustomGraphicImage(nestedNetworkPaint.getAnchorRect(), (float)doubleBuff2[0], (float)doubleBuff2[1], nestedNetworkPaint);
}
// draw custom graphics on top of nested networks
// don't allow our custom graphics to mutate while we iterate over them:
// synchronized (nodeDetails.customGraphicsLock(cyNode)) {
synchronized (nodeDetails) {
// This method should return CustomGraphics in rendering order:
final Map<VisualProperty<CyCustomGraphics>, CustomGraphicsInfo> cgMap = nodeDetails.getCustomGraphics(cyNode);
final List<CustomGraphicsInfo> infoList = new ArrayList<>(cgMap.values());
for (final CustomGraphicsInfo cgInfo : infoList) {
// MKTODO I guess there's no way around doing this? The charts need access to the underlying table model.
CyNetworkView netViewForCharts = netView.getMutableNetworkView();
View<CyNode> mutableNode = netView.getMutableNodeView(cyNode.getSUID());
if(mutableNode != null) {
List<CustomGraphicLayer> layers = cgInfo.createLayers(netViewForCharts, mutableNode, nodeDetails, dependencies);
for (CustomGraphicLayer layer : layers) {
float offsetVectorX = nodeDetails.graphicOffsetVectorX(cyNode);
float offsetVectorY = nodeDetails.graphicOffsetVectorY(cyNode);
doubleBuff1[0] = floatBuff1[0];
doubleBuff1[1] = floatBuff1[1];
doubleBuff1[2] = floatBuff1[2];
doubleBuff1[3] = floatBuff1[3];
lemma_computeAnchor(Position.CENTER, doubleBuff1, doubleBuff2);
float xOffset = (float) (doubleBuff2[0] + offsetVectorX);
float yOffset = (float) (doubleBuff2[1] + offsetVectorY);
nodeShape = createCustomGraphicsShape(nodeShape, layer, -xOffset, -yOffset);
grafx.drawCustomGraphicFull(netViewForCharts, mutableNode, nodeShape, layer, xOffset, yOffset);
}
}
}
}
}
}
private static Shape createCustomGraphicsShape(final Shape nodeShape, final CustomGraphicLayer layer,
float xOffset, float yOffset) {
final Rectangle2D nsb = nodeShape.getBounds2D();
final Rectangle2D cgb = layer.getBounds2D();
final AffineTransform xform = new AffineTransform();
xform.scale(cgb.getWidth() / nsb.getWidth(), cgb.getHeight() / nsb.getHeight());
xform.translate(xOffset, yOffset);
return xform.createTransformedShape(nodeShape);
}
}
| ding-impl/ding-presentation-impl/src/main/java/org/cytoscape/graph/render/stateful/GraphRenderer.java | package org.cytoscape.graph.render.stateful;
import static org.cytoscape.graph.render.stateful.RenderDetailFlags.*;
/*
* #%L
* Cytoscape Ding View/Presentation Impl (ding-presentation-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2013 The Cytoscape Consortium
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.awt.Font;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.cytoscape.ding.impl.work.DiscreteProgressMonitor;
import org.cytoscape.ding.impl.work.ProgressMonitor;
import org.cytoscape.ding.internal.util.MurmurHash3;
import org.cytoscape.graph.render.immed.EdgeAnchors;
import org.cytoscape.graph.render.immed.GraphGraphics;
import org.cytoscape.graph.render.stateful.GraphLOD.RenderEdges;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNode;
import org.cytoscape.util.intr.LongHash;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewSnapshot;
import org.cytoscape.view.model.SnapshotEdgeInfo;
import org.cytoscape.view.model.View;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.model.spacial.SpacialIndex2DEnumerator;
import org.cytoscape.view.presentation.customgraphics.CustomGraphicLayer;
import org.cytoscape.view.presentation.customgraphics.CyCustomGraphics;
import org.cytoscape.view.presentation.property.ArrowShapeVisualProperty;
import org.cytoscape.view.presentation.property.values.ArrowShape;
import org.cytoscape.view.presentation.property.values.Justification;
import org.cytoscape.view.presentation.property.values.Position;
import org.cytoscape.view.vizmap.VisualPropertyDependency;
/**
* This class contains a chunk of procedural code that stitches together
* several external modules in an effort to efficiently render graphs.
*/
public final class GraphRenderer {
// No constructor.
private GraphRenderer() {
}
// /**
// * Renders a graph.
// * @param netView the network view; nodes in this graph must correspond to
// * objKeys in nodePositions (the SpacialIndex2D parameter) and vice versa.
// * @param nodePositions defines the positions and extents of nodes in graph;
// * each entry (objKey) in this structure must correspond to a node in graph
// * (the CyNetwork parameter) and vice versa; the order in which nodes are
// * rendered is defined by a non-reversed overlap query on this structure.
// * @param lod defines the different levels of detail; an appropriate level
// * of detail is chosen based on the results of method calls on this
// * object.
// * @param nodeDetails defines details of nodes such as colors, node border
// * thickness, and shape; the node arguments passed to methods on this
// * object will be nodes in the graph parameter.
// * @param edgeDetails defines details of edges such as colors, thickness,
// * and arrow type; the edge arguments passed to methods on this
// * object will be edges in the graph parameter.
// * @param nodeBuff this is a computational helper that is required in the
// * implementation of this method; when this method returns, nodeBuff is
// * in a state such that an edge in graph has been rendered by this method
// * if and only if it touches at least one node in this nodeBuff set;
// * no guarantee made regarding edgeless nodes.
// * @param grafx the graphics context that is to render this graph.
// * @param bgPaint the background paint to use when calling grafx.clear().
// * @param xCenter the xCenter parameter to use when calling grafx.clear().
// * @param yCenter the yCenter parameter to use when calling grafx.clear().
// * @param scaleFactor the scaleFactor parameter to use when calling
// * grafx.clear().
// * @param dependencies
// * @return bits representing the level of detail that was rendered; the
// * return value is a bitwise-or'ed value of the LOD_* constants.
// */
// public final static void renderGraph(final CyNetworkViewSnapshot netView,
// final RenderDetailFlags flags,
// final NodeDetails nodeDetails,
// final EdgeDetails edgeDetails,
// final GraphGraphics grafx,
// final Set<VisualPropertyDependency<?>> dependencies) {
//
//// RenderDetailFlags flags = RenderDetailFlags.create(netView, grafx.getTransform(), lod, edgeDetails);
//
// if (flags.renderEdges() >= 0) {
// renderEdges(grafx, netView, flags, nodeDetails, edgeDetails);
// }
// renderNodes(grafx, netView, flags, nodeDetails, edgeDetails, dependencies);
// }
public static void renderEdges(ProgressMonitor pm, GraphGraphics grafx, CyNetworkViewSnapshot netView,
RenderDetailFlags flags, NodeDetails nodeDetails, EdgeDetails edgeDetails) {
// Render the edges first. No edge shall be rendered twice. Render edge labels.
// A label is not necessarily on top of every edge; it is only on top of the edge it belongs to.
if(flags.renderEdges() == RenderEdges.NONE) {
return;
}
final float[] floatBuff1 = new float[4];
final float[] floatBuff2 = new float[4];
final float[] floatBuff3 = new float[2];
final float[] floatBuff4 = new float[2];
final float[] floatBuff5 = new float[8];
final double[] doubleBuff1 = new double[4];
final double[] doubleBuff2 = new double[2];
final GeneralPath path2d = new GeneralPath();
final LongHash nodeBuff = new LongHash();
final SpacialIndex2DEnumerator<Long> nodeHits;
Rectangle2D.Float area = grafx.getTransform().getNetworkVisibleAreaNodeCoords();
if (flags.renderEdges() == RenderEdges.ALL)
// We want to render edges in the same order (back to front) that
// we would use to render just edges on visible nodes; this is assuming
// that our spacial index has the subquery order-preserving property.
nodeHits = netView.getSpacialIndex2D().queryAll();
else
nodeHits = netView.getSpacialIndex2D().queryOverlap(area.x, area.y, area.x + area.width, area.y + area.height); // MKTODO why are we querying twice?
if (flags.not(LOD_HIGH_DETAIL)) { // Low detail.
ProgressMonitor[] subPms = pm.split(1,0); // no labels at all, still need labelPm for debug panel
ProgressMonitor shapePm = subPms[0];
ProgressMonitor labelPm = subPms[1];
shapePm.start("Line");
DiscreteProgressMonitor shapeDpm = shapePm.toDiscrete(nodeHits.size());
while (nodeHits.hasNext()) {
if(pm.isCancelled()) {
return;
}
final long nodeSuid = nodeHits.nextExtents(floatBuff1);
// Casting to double and then back we could achieve better accuracy
// at the expense of performance.
final float nodeX = (floatBuff1[0] + floatBuff1[2]) / 2;
final float nodeY = (floatBuff1[1] + floatBuff1[3]) / 2;
Iterable<View<CyEdge>> touchingEdges = netView.getAdjacentEdgeIterable(nodeSuid);
for ( View<CyEdge> edge : touchingEdges ) {
if (!edgeDetails.isVisible(edge))
continue;
SnapshotEdgeInfo edgeInfo = netView.getEdgeInfo(edge);
final long otherNode = nodeSuid ^ edgeInfo.getSourceViewSUID() ^ edgeInfo.getTargetViewSUID();
if (nodeBuff.get(otherNode) < 0) { // Has not yet been rendered.
netView.getSpacialIndex2D().get(otherNode, floatBuff2);
grafx.drawEdgeLow(nodeX, nodeY,
// Again, casting issue - tradeoff between
// accuracy and performance.
(floatBuff2[0] + floatBuff2[2]) / 2,
(floatBuff2[1] + floatBuff2[3]) / 2,
edgeDetails.getColorLowDetail(netView, edge));
}
}
nodeBuff.put(nodeSuid);
shapeDpm.increment();
}
shapePm.done();
labelPm.emptyTask("Label");
} else { // High detail.
ProgressMonitor[] subPms = pm.split(1,1); // labels usually take longer
ProgressMonitor shapePm = subPms[0];
ProgressMonitor labelPm = subPms[1];
DiscreteProgressMonitor shapeDpm = shapePm.toDiscrete(nodeHits.size());
DiscreteProgressMonitor labelDpm = labelPm.toDiscrete(nodeHits.size());
byte[] haystackDataBuff = new byte[16];
while (nodeHits.hasNext()) {
if(pm.isCancelled())
return;
final long nodeSuid = nodeHits.nextExtents(floatBuff1);
final View<CyNode> node = netView.getNodeView(nodeSuid);
final byte nodeShape = nodeDetails.getShape(node);
Iterable<View<CyEdge>> touchingEdges = netView.getAdjacentEdgeIterable(node);
for (View<CyEdge> edge : touchingEdges) {
if(pm.isCancelled()) {
return;
}
if (!edgeDetails.isVisible(edge))
continue;
SnapshotEdgeInfo edgeInfo = netView.getEdgeInfo(edge);
long edgeSuid = edgeInfo.getSUID();
var sourceViewSUID = edgeInfo.getSourceViewSUID();
var targetViewSUID = edgeInfo.getTargetViewSUID();
final long otherNode = nodeSuid ^ sourceViewSUID ^ targetViewSUID;
final View<CyNode> otherCyNode = netView.getNodeView(otherNode);
boolean haystack = edgeDetails.isHaystack(edge);
if (nodeBuff.get(otherNode) < 0) { // Has not yet been rendered.
shapePm.start("Line");
if (!netView.getSpacialIndex2D().get(otherNode, floatBuff2))
continue;
// throw new IllegalStateException("nodePositions not recognizing node that exists in graph: "+otherCyNode.toString());
final byte otherNodeShape = nodeDetails.getShape(otherCyNode);
// Compute node shapes, center positions, and extents.
final byte srcShape;
// Compute node shapes, center positions, and extents.
final byte trgShape;
final float[] srcExtents;
final float[] trgExtents;
if (nodeSuid == sourceViewSUID) {
srcShape = nodeShape;
trgShape = otherNodeShape;
srcExtents = floatBuff1;
trgExtents = floatBuff2;
} else { // node == graph.edgeTarget(edge).
srcShape = otherNodeShape;
trgShape = nodeShape;
srcExtents = floatBuff2;
trgExtents = floatBuff1;
}
// Compute visual attributes that do not depend on LOD.
final float thickness = (float) edgeDetails.getWidth(edge);
final Stroke edgeStroke = edgeDetails.getStroke(edge);
final Paint segPaint = edgeDetails.getPaint(edge);
// Compute arrows.
final ArrowShape srcArrow;
final ArrowShape trgArrow;
final float srcArrowSize;
final float trgArrowSize;
final Paint srcArrowPaint;
final Paint trgArrowPaint;
if (flags.not(LOD_EDGE_ARROWS) || haystack) { // Not rendering arrows.
trgArrow = srcArrow = ArrowShapeVisualProperty.NONE;
trgArrowSize = srcArrowSize = 0.0f;
trgArrowPaint = srcArrowPaint = null;
} else { // Rendering edge arrows.
srcArrow = edgeDetails.getSourceArrowShape(edge);
trgArrow = edgeDetails.getTargetArrowShape(edge);
srcArrowSize = ((srcArrow == ArrowShapeVisualProperty.NONE) ? 0.0f : edgeDetails.getSourceArrowSize(edge));
trgArrowSize = ((trgArrow == ArrowShapeVisualProperty.NONE) ? 0.0f : edgeDetails.getTargetArrowSize(edge));
srcArrowPaint = ((srcArrow == ArrowShapeVisualProperty.NONE) ? null : edgeDetails.getSourceArrowPaint(edge));
trgArrowPaint = ((trgArrow == ArrowShapeVisualProperty.NONE) ? null : edgeDetails.getTargetArrowPaint(edge));
}
// Compute the anchors to use when rendering edge.
final EdgeAnchors anchors = flags.not(LOD_EDGE_ANCHORS) ? null : edgeDetails.getAnchors(netView, edge);
if(haystack) {
float radiusModifier = edgeDetails.getHaystackRadius(edge);
if (!computeEdgeEndpointsHaystack(srcExtents, trgExtents, floatBuff3, floatBuff4,
nodeSuid, otherNode, edgeSuid, haystackDataBuff, radiusModifier))
continue;
}
else {
if (!computeEdgeEndpoints(srcExtents, srcShape, srcArrow,
srcArrowSize, anchors, trgExtents, trgShape,
trgArrow, trgArrowSize, floatBuff3, floatBuff4))
continue;
}
final float srcXAdj = floatBuff3[0];
final float srcYAdj = floatBuff3[1];
final float trgXAdj = floatBuff4[0];
final float trgYAdj = floatBuff4[1];
grafx.drawEdgeFull(srcArrow, srcArrowSize, srcArrowPaint, trgArrow,
trgArrowSize, trgArrowPaint, srcXAdj, srcYAdj,
anchors, trgXAdj, trgYAdj, thickness, edgeStroke, segPaint);
// Take care of edge anchor rendering.
if (anchors != null) {
for (int k = 0; k < anchors.numAnchors(); k++) {
final float anchorSize;
if ((anchorSize = edgeDetails.getAnchorSize(edge, k)) > 0.0f) {
anchors.getAnchor(k, floatBuff4);
grafx.drawNodeFull(GraphGraphics.SHAPE_RECTANGLE,
(float) (floatBuff4[0] - (anchorSize / 2.0d)),
(float) (floatBuff4[1] - (anchorSize / 2.0d)),
(float) (floatBuff4[0] + (anchorSize / 2.0d)),
(float) (floatBuff4[1] + (anchorSize / 2.0d)),
edgeDetails.getAnchorPaint(edge, k), 0.0f, null, null);
}
}
}
shapePm.done();
labelPm.start("Label");
// Take care of label rendering.
if (flags.has(LOD_EDGE_LABELS)) {
final int labelCount = edgeDetails.getLabelCount(edge);
for (int labelInx = 0; labelInx < labelCount; labelInx++) {
if(pm.isCancelled()) {
return;
}
final String text = edgeDetails.getLabelText(edge);
final Font font = edgeDetails.getLabelFont(edge);
final double fontScaleFactor = edgeDetails.getLabelScaleFactor(edge);
final Paint paint = edgeDetails.getLabelPaint(edge);
final Position textAnchor = edgeDetails.getLabelTextAnchor(edge);
final Position edgeAnchor = edgeDetails.getLabelEdgeAnchor(edge);
final float offsetVectorX = edgeDetails.getLabelOffsetVectorX(edge);
final float offsetVectorY = edgeDetails.getLabelOffsetVectorY(edge);
final double theta = edgeDetails.getLabelRotation(edge)*.01745329252;
final Justification justify;
if (text.indexOf('\n') >= 0)
justify = edgeDetails.getLabelJustify(edge);
else
justify = Justification.JUSTIFY_CENTER;
final double edgeAnchorPointX;
final double edgeAnchorPointY;
final double edgeLabelWidth = edgeDetails.getLabelWidth(edge);
// Note that we reuse the position enum here. West == source and East == target
// This is sort of safe since we don't provide an API for changing this
// in any case.
if (edgeAnchor == Position.WEST) { edgeAnchorPointX = srcXAdj; edgeAnchorPointY = srcYAdj;
} else if (edgeAnchor == Position.EAST) { edgeAnchorPointX = trgXAdj; edgeAnchorPointY = trgYAdj;
} else if (edgeAnchor == Position.CENTER) {
if (!GraphGraphics.getEdgePath(srcArrow, srcArrowSize, trgArrow,
trgArrowSize, srcXAdj, srcYAdj, anchors, trgXAdj, trgYAdj, path2d)) {
continue;
}
// Count the number of path segments. This count
// includes the initial SEG_MOVETO. So, for example, a
// path composed of 2 cubic curves would have a numPaths
// of 3. Note that numPaths will be at least 2 in all
// cases.
final int numPaths;
{
final PathIterator pathIter = path2d.getPathIterator(null);
int numPathsTemp = 0;
while (!pathIter.isDone()) {
numPathsTemp++; // pathIter.currentSegment().
pathIter.next();
}
numPaths = numPathsTemp;
}
// Compute "midpoint" of edge.
if ((numPaths % 2) != 0) {
final PathIterator pathIter = path2d.getPathIterator(null);
for (int i = numPaths / 2; i > 0; i--)
pathIter.next();
final int subPathType = pathIter.currentSegment(floatBuff5);
if (subPathType == PathIterator.SEG_LINETO) {
edgeAnchorPointX = floatBuff5[0];
edgeAnchorPointY = floatBuff5[1];
} else if (subPathType == PathIterator.SEG_QUADTO) {
edgeAnchorPointX = floatBuff5[2];
edgeAnchorPointY = floatBuff5[3];
} else if (subPathType == PathIterator.SEG_CUBICTO) {
edgeAnchorPointX = floatBuff5[4];
edgeAnchorPointY = floatBuff5[5];
} else
throw new IllegalStateException("got unexpected PathIterator segment type: " + subPathType);
} else { // numPaths % 2 == 0.
final PathIterator pathIter = path2d.getPathIterator(null);
for (int i = numPaths / 2; i > 0; i--) {
if (i == 1) {
final int subPathType = pathIter.currentSegment(floatBuff5);
if ((subPathType == PathIterator.SEG_MOVETO)
|| (subPathType == PathIterator.SEG_LINETO)) {
floatBuff5[6] = floatBuff5[0];
floatBuff5[7] = floatBuff5[1];
} else if (subPathType == PathIterator.SEG_QUADTO) {
floatBuff5[6] = floatBuff5[2];
floatBuff5[7] = floatBuff5[3];
} else if (subPathType == PathIterator.SEG_CUBICTO) {
floatBuff5[6] = floatBuff5[4];
floatBuff5[7] = floatBuff5[5];
} else
throw new IllegalStateException("got unexpected PathIterator segment type: " + subPathType);
}
pathIter.next();
}
final int subPathType = pathIter.currentSegment(floatBuff5);
if (subPathType == PathIterator.SEG_LINETO) {
edgeAnchorPointX = (0.5d * floatBuff5[6]) + (0.5d * floatBuff5[0]);
edgeAnchorPointY = (0.5d * floatBuff5[7]) + (0.5d * floatBuff5[1]);
} else if (subPathType == PathIterator.SEG_QUADTO) {
edgeAnchorPointX = (0.25d * floatBuff5[6]) + (0.5d * floatBuff5[0]) + (0.25d * floatBuff5[2]);
edgeAnchorPointY = (0.25d * floatBuff5[7]) + (0.5d * floatBuff5[1]) + (0.25d * floatBuff5[3]);
} else if (subPathType == PathIterator.SEG_CUBICTO) {
edgeAnchorPointX = (0.125d * floatBuff5[6]) + (0.375d * floatBuff5[0]) + (0.375d * floatBuff5[2]) + (0.125d * floatBuff5[4]);
edgeAnchorPointY = (0.125d * floatBuff5[7]) + (0.375d * floatBuff5[1]) + (0.375d * floatBuff5[3]) + (0.125d * floatBuff5[5]);
} else
throw new IllegalStateException("got unexpected PathIterator segment type: " + subPathType);
}
} else
throw new IllegalStateException("encountered an invalid EDGE_ANCHOR_* constant: " + edgeAnchor);
final MeasuredLineCreator measuredText =
new MeasuredLineCreator(text,font,
grafx.getFontRenderContextFull(),
fontScaleFactor,
flags.has(LOD_TEXT_AS_SHAPE),
edgeLabelWidth);
doubleBuff1[0] = -0.5d * measuredText.getMaxLineWidth();
doubleBuff1[1] = -0.5d * measuredText.getTotalHeight();
doubleBuff1[2] = 0.5d * measuredText.getMaxLineWidth();
doubleBuff1[3] = 0.5d * measuredText.getTotalHeight();
lemma_computeAnchor(textAnchor, doubleBuff1, doubleBuff2);
final double textXCenter = edgeAnchorPointX - doubleBuff2[0] + offsetVectorX;
final double textYCenter = edgeAnchorPointY - doubleBuff2[1] + offsetVectorY;
TextRenderingUtils.renderText(grafx, measuredText,
font, fontScaleFactor,
(float) textXCenter,
(float) textYCenter,
justify, paint, theta,
flags.has(LOD_TEXT_AS_SHAPE));
}
}
labelPm.done();
}
}
nodeBuff.put(nodeSuid);
shapeDpm.increment();
labelDpm.increment();
}
}
}
public static void renderNodes(ProgressMonitor pm, GraphGraphics grafx, CyNetworkViewSnapshot netView,
RenderDetailFlags flags, NodeDetails nodeDetails, EdgeDetails edgeDetails, Set<VisualPropertyDependency<?>> dependencies) {
// Render nodes and labels. A label is not necessarily on top of every
// node; it is only on top of the node it belongs to.
final float[] floatBuff1 = new float[4];
final double[] doubleBuff1 = new double[4];
final double[] doubleBuff2 = new double[2];
Rectangle2D.Float area = grafx.getTransform().getNetworkVisibleAreaNodeCoords();
SpacialIndex2DEnumerator<Long> nodeHits = netView.getSpacialIndex2D().queryOverlap(area.x, area.y, area.x + area.width, area.y + area.height);
if (flags.not(LOD_HIGH_DETAIL)) { // Low detail.
ProgressMonitor[] subPms = pm.split(1,0); // no labels at all, still need labelPm for debug panel
ProgressMonitor shapePm = subPms[0];
ProgressMonitor labelPm = subPms[1];
shapePm.start("Shape");
final int nodeHitCount = nodeHits.size();
DiscreteProgressMonitor shapeDpm = shapePm.toDiscrete(nodeHitCount);
for (int i = 0; i < nodeHitCount; i++) {
if(pm.isCancelled())
return;
final View<CyNode> node = netView.getNodeView( nodeHits.nextExtents(floatBuff1) );
if ((floatBuff1[0] != floatBuff1[2]) && (floatBuff1[1] != floatBuff1[3]))
grafx.drawNodeLow(floatBuff1[0], floatBuff1[1], floatBuff1[2],
floatBuff1[3], nodeDetails.getColorLowDetail(netView, node));
shapeDpm.increment();
}
shapePm.done();
labelPm.emptyTask("Label");
} else { // High detail.
ProgressMonitor[] subPms = pm.split(1,2); // labels usually take longer
ProgressMonitor shapePm = subPms[0];
ProgressMonitor labelPm = subPms[1];
DiscreteProgressMonitor shapeDpm = shapePm.toDiscrete(nodeHits.size());
DiscreteProgressMonitor labelDpm = labelPm.toDiscrete(nodeHits.size());
while (nodeHits.hasNext()) {
if(pm.isCancelled())
return;
final long node = nodeHits.nextExtents(floatBuff1);
final View<CyNode> cyNode = netView.getNodeView(node);
shapePm.start("Shape");
renderNodeHigh(netView, grafx, cyNode, floatBuff1, doubleBuff1, doubleBuff2, nodeDetails, flags, dependencies);
shapeDpm.increment();
shapePm.done();
labelPm.start("Label");
// Take care of label rendering.
if (flags.has(LOD_NODE_LABELS)) { // Potential label rendering.
final int labelCount = nodeDetails.getLabelCount(cyNode);
for (int labelInx = 0; labelInx < labelCount; labelInx++) {
final String text = nodeDetails.getLabelText(cyNode);
final Font font = nodeDetails.getLabelFont(cyNode);
final double fontScaleFactor = nodeDetails.getLabelScaleFactor(cyNode);
final Paint paint = nodeDetails.getLabelPaint(cyNode);
final Position textAnchor = nodeDetails.getLabelTextAnchor(cyNode);
final Position nodeAnchor = nodeDetails.getLabelNodeAnchor(cyNode);
final float offsetVectorX = nodeDetails.getLabelOffsetVectorX(cyNode);
final float offsetVectorY = nodeDetails.getLabelOffsetVectorY(cyNode);
final double theta = nodeDetails.getLabelRotation(cyNode)*.01745329252;
final Justification justify;
if (text.indexOf('\n') >= 0)
justify = nodeDetails.getLabelJustify(cyNode);
else
justify = Justification.JUSTIFY_CENTER;
final double nodeLabelWidth = nodeDetails.getLabelWidth(cyNode);
doubleBuff1[0] = floatBuff1[0];
doubleBuff1[1] = floatBuff1[1];
doubleBuff1[2] = floatBuff1[2];
doubleBuff1[3] = floatBuff1[3];
lemma_computeAnchor(nodeAnchor, doubleBuff1, doubleBuff2);
final double nodeAnchorPointX = doubleBuff2[0];
final double nodeAnchorPointY = doubleBuff2[1];
final MeasuredLineCreator measuredText = new MeasuredLineCreator(
text, font, grafx.getFontRenderContextFull(), fontScaleFactor,
flags.has(LOD_TEXT_AS_SHAPE), nodeLabelWidth);
doubleBuff1[0] = -0.5d * measuredText.getMaxLineWidth();
doubleBuff1[1] = -0.5d * measuredText.getTotalHeight();
doubleBuff1[2] = 0.5d * measuredText.getMaxLineWidth();
doubleBuff1[3] = 0.5d * measuredText.getTotalHeight();
lemma_computeAnchor(textAnchor, doubleBuff1, doubleBuff2);
final double textXCenter = nodeAnchorPointX - doubleBuff2[0] + offsetVectorX;
final double textYCenter = nodeAnchorPointY - doubleBuff2[1] + offsetVectorY;
TextRenderingUtils.renderText(grafx, measuredText, font,
fontScaleFactor,
(float) textXCenter,
(float) textYCenter, justify,
paint,theta,
flags.has(LOD_TEXT_AS_SHAPE));
}
}
labelDpm.increment();
labelPm.done();
}
}
}
/**
*
* @param anchor
* @param input4x An array of 4 elements: x0,y0,x1, y1 of a rectangle
* @param rtrn2x An array of 2 element. x and y coordinates of the center of the object.
*/
public final static void lemma_computeAnchor(final Position anchor, final double[] input4x,
final double[] rtrn2x) {
switch (anchor) {
case CENTER:
rtrn2x[0] = (input4x[0] + input4x[2]) / 2.0d;
rtrn2x[1] = (input4x[1] + input4x[3]) / 2.0d;
break;
case SOUTH:
rtrn2x[0] = (input4x[0] + input4x[2]) / 2.0d;
rtrn2x[1] = input4x[3];
break;
case SOUTH_EAST:
rtrn2x[0] = input4x[2];
rtrn2x[1] = input4x[3];
break;
case EAST:
rtrn2x[0] = input4x[2];
rtrn2x[1] = (input4x[1] + input4x[3]) / 2.0d;
break;
case NORTH_EAST:
rtrn2x[0] = input4x[2];
rtrn2x[1] = input4x[1];
break;
case NORTH:
rtrn2x[0] = (input4x[0] + input4x[2]) / 2.0d;
rtrn2x[1] = input4x[1];
break;
case NORTH_WEST:
rtrn2x[0] = input4x[0];
rtrn2x[1] = input4x[1];
break;
case WEST:
rtrn2x[0] = input4x[0];
rtrn2x[1] = (input4x[1] + input4x[3]) / 2.0d;
break;
case SOUTH_WEST:
rtrn2x[0] = input4x[0];
rtrn2x[1] = input4x[3];
break;
default:
throw new IllegalStateException("encoutered an invalid ANCHOR_* constant: "
+ anchor);
}
}
public final static boolean computeEdgeEndpointsHaystack(final float[] srcNodeExtents, final float[] trgNodeExtents,
final float[] rtnValSrc, final float[] rtnValTrg, long srcSuid, long trgSuid,
long edgeSuid, byte[] dataBuff, float radiusModifier) {
haystackEndpoint(srcNodeExtents, rtnValSrc, dataBuff, srcSuid, edgeSuid, radiusModifier);
haystackEndpoint(trgNodeExtents, rtnValTrg, dataBuff, trgSuid, edgeSuid, radiusModifier);
return true;
}
/**
* Computes a 'random' point around the circumference of a circle within the node.
*/
private final static void haystackEndpoint(float[] nodeExtents, float[] rtnVal,
byte[] dataBuff, long nodeSuid, long edgeSuid, float radiusModifier) {
final float xMin = nodeExtents[0];
final float yMin = nodeExtents[1];
final float xMax = nodeExtents[2];
final float yMax = nodeExtents[3];
final float centerX = (xMin + xMax) / 2.0f;
final float centerY = (yMin + yMax) / 2.0f;
final float width = xMax - xMin;
final float height = yMax - yMin;
final float radius = (Math.min(width, height) / 2.0f) * radiusModifier;
// Hash the node and edge SUIDs to a value between 0.0 and 1.0. This is done instead of
// generating a random number so that the edge endpoints stay consistent between frames.
float h1 = hashSuids(dataBuff, nodeSuid, edgeSuid, 99);
// Use the hash to get a 'random' point around the circumference
// of a circle that lies within the node boundaries.
double theta = h1 * Math.PI * 2;
double x = centerX + Math.cos(theta) * radius;
double y = centerY + Math.sin(theta) * radius;
rtnVal[0] = (float) x;
rtnVal[1] = (float) y;
}
private static void longToBytes(long l, byte[] buff, int offset) {
for (int i = offset + 7; i >= offset; i--) {
buff[i] = (byte) (l & 0xFF);
l >>= 8;
}
}
/**
* Returns a hashed value of the given suids in the range 0.0 to 1.0
*/
private static float hashSuids(byte[] dataBuff, long nodeSuid, long edgeSuid, int seed) {
longToBytes(nodeSuid, dataBuff, 0);
longToBytes(edgeSuid, dataBuff, 8);
int hash = MurmurHash3.murmurhash3_x86_32(dataBuff, 0, dataBuff.length, seed);
float r = Math.abs((float) hash / Integer.MAX_VALUE);
return r;
}
/**
* Calculates the edge endpoints given two nodes, any edge anchors, and any arrows.
*
* @param grafx The GraphGraphics being used to render everything. Used only to
* calculate the edge intersection of the node.
* @param srcNodeExtents The extents of the source node.
* @param srcNodeShape The node shape type.
* @param srcArrow The source arrow type.
* @param srcArrowSize The source arrow size.
* @param anchors an EdgeAnchors object listing any anchors for the edge, possibly null.
* @param trgNodeExtents The extends of the target node.
* @param trgNodeShape The target node type.
* @param trgArrow The target arrow type.
* @param trgArrowSize The target arrow size.
* @param rtnValSrc The array where X,Y positions of the source end of the edge are stored.
* @param rtnValTrg The array where X,Y positions of the target end of the edge are stored.
*
* @return DOCUMENT ME!
*/
public final static boolean computeEdgeEndpoints(final float[] srcNodeExtents,
final byte srcNodeShape, final ArrowShape srcArrow,
final float srcArrowSize, EdgeAnchors anchors,
final float[] trgNodeExtents,
final byte trgNodeShape, final ArrowShape trgArrow,
final float trgArrowSize,
final float[] rtnValSrc,
final float[] rtnValTrg) {
final float srcX = (float) ((((double) srcNodeExtents[0]) + srcNodeExtents[2]) / 2.0d);
final float srcY = (float) ((((double) srcNodeExtents[1]) + srcNodeExtents[3]) / 2.0d);
final float trgX = (float) ((((double) trgNodeExtents[0]) + trgNodeExtents[2]) / 2.0d);
final float trgY = (float) ((((double) trgNodeExtents[1]) + trgNodeExtents[3]) / 2.0d);
final float srcXOut;
final float srcYOut;
final float trgXOut;
final float trgYOut;
final float[] floatBuff = new float[2];
if ((anchors != null) && (anchors.numAnchors() == 0))
anchors = null;
if (anchors == null) {
srcXOut = trgX;
srcYOut = trgY;
trgXOut = srcX;
trgYOut = srcY;
} else {
anchors.getAnchor(0, floatBuff);
srcXOut = floatBuff[0];
srcYOut = floatBuff[1];
anchors.getAnchor(anchors.numAnchors() - 1, floatBuff);
trgXOut = floatBuff[0];
trgYOut = floatBuff[1];
}
calcIntersection(srcNodeShape, srcNodeExtents, srcX, srcY, srcXOut, srcYOut, floatBuff);
final float srcXAdj = floatBuff[0];
final float srcYAdj = floatBuff[1];
calcIntersection(trgNodeShape, trgNodeExtents, trgX, trgY, trgXOut, trgYOut, floatBuff);
final float trgXAdj = floatBuff[0];
final float trgYAdj = floatBuff[1];
rtnValSrc[0] = srcXAdj;
rtnValSrc[1] = srcYAdj;
rtnValTrg[0] = trgXAdj;
rtnValTrg[1] = trgYAdj;
return true;
}
private static void calcIntersection(byte nodeShape,
float[] nodeExtents, float x, float y,
float xOut, float yOut, float[] retVal) {
if ((nodeExtents[0] == nodeExtents[2]) ||
(nodeExtents[1] == nodeExtents[3])) {
retVal[0] = x;
retVal[1] = y;
} else {
if (!GraphGraphics.computeEdgeIntersection(nodeShape, nodeExtents[0],
nodeExtents[1], nodeExtents[2],
nodeExtents[3], 0.0f, xOut, yOut,
retVal)) {
final float newXOut;
final float newYOut;
final double xCenter = (((double) nodeExtents[0]) + nodeExtents[2]) / 2.0d;
final double yCenter = (((double) nodeExtents[1]) + nodeExtents[3]) / 2.0d;
final double desiredDist = Math.max(((double) nodeExtents[2])
- nodeExtents[0],
((double) nodeExtents[3])
- nodeExtents[1]);
final double dX = xOut - xCenter;
final double dY = yOut - yCenter;
final double len = Math.sqrt((dX * dX) + (dY * dY));
if (len == 0.0d) {
newXOut = (float) (xOut + desiredDist);
newYOut = yOut;
} else {
newXOut = (float) (((dX / len) * desiredDist) + xOut);
newYOut = (float) (((dY / len) * desiredDist) + yOut);
}
GraphGraphics.computeEdgeIntersection(nodeShape, nodeExtents[0],
nodeExtents[1], nodeExtents[2],
nodeExtents[3], 0.0f, newXOut,
newYOut, retVal);
}
}
}
private final static float[] s_floatTemp = new float[6];
private final static int[] s_segTypeBuff = new int[200];
private final static float[] s_floatBuff2 = new float[1200];
/**
* DOCUMENT ME!
*
* @param origPath DOCUMENT ME!
* @param rtnVal DOCUMENT ME!
*/
public final static void computeClosedPath(final PathIterator origPath, final GeneralPath rtnVal) {
synchronized (s_floatTemp) {
// First fill our buffers with the coordinates and segment types.
int segs = 0;
int offset = 0;
if ((s_segTypeBuff[segs++] = origPath.currentSegment(s_floatTemp)) != PathIterator.SEG_MOVETO)
throw new IllegalStateException("expected a SEG_MOVETO at the beginning of origPath");
for (int i = 0; i < 2; i++)
s_floatBuff2[offset++] = s_floatTemp[i];
origPath.next();
while (!origPath.isDone()) {
final int segType = origPath.currentSegment(s_floatTemp);
s_segTypeBuff[segs++] = segType;
if ((segType == PathIterator.SEG_MOVETO) || (segType == PathIterator.SEG_CLOSE))
throw new IllegalStateException("did not expect SEG_MOVETO or SEG_CLOSE");
// This is a rare case where I rely on the actual constant values
// to do a computation efficiently.
final int coordCount = segType * 2;
for (int i = 0; i < coordCount; i++)
s_floatBuff2[offset++] = s_floatTemp[i];
origPath.next();
}
rtnVal.reset();
offset = 0;
// Now add the forward path to rtnVal.
for (int i = 0; i < segs; i++) {
switch (s_segTypeBuff[i]) {
case PathIterator.SEG_MOVETO:
rtnVal.moveTo(s_floatBuff2[offset++], s_floatBuff2[offset++]);
break;
case PathIterator.SEG_LINETO:
rtnVal.lineTo(s_floatBuff2[offset++], s_floatBuff2[offset++]);
break;
case PathIterator.SEG_QUADTO:
rtnVal.quadTo(s_floatBuff2[offset++], s_floatBuff2[offset++],
s_floatBuff2[offset++], s_floatBuff2[offset++]);
break;
default: // PathIterator.SEG_CUBICTO.
rtnVal.curveTo(s_floatBuff2[offset++], s_floatBuff2[offset++],
s_floatBuff2[offset++], s_floatBuff2[offset++],
s_floatBuff2[offset++], s_floatBuff2[offset++]);
break;
}
}
// Now add the return path.
for (int i = segs - 1; i > 0; i--) {
switch (s_segTypeBuff[i]) {
case PathIterator.SEG_LINETO:
offset -= 2;
rtnVal.lineTo(s_floatBuff2[offset - 2], s_floatBuff2[offset - 1]);
break;
case PathIterator.SEG_QUADTO:
offset -= 4;
rtnVal.quadTo(s_floatBuff2[offset], s_floatBuff2[offset + 1],
s_floatBuff2[offset - 2], s_floatBuff2[offset - 1]);
break;
default: // PathIterator.SEG_CUBICTO.
offset -= 6;
rtnVal.curveTo(s_floatBuff2[offset + 2], s_floatBuff2[offset + 3],
s_floatBuff2[offset], s_floatBuff2[offset + 1],
s_floatBuff2[offset - 2], s_floatBuff2[offset - 1]);
break;
}
}
rtnVal.closePath();
}
}
static final boolean _computeEdgeIntersection(final float nodeX, final float nodeY,
final float offset, final float ptX,
final float ptY, final boolean alwaysCompute,
final float[] returnVal) {
if (offset == 0.0f) {
returnVal[0] = nodeX;
returnVal[1] = nodeY;
return true;
} else {
final double dX = ptX - nodeX;
final double dY = ptY - nodeY;
final double len = Math.sqrt((dX * dX) + (dY * dY));
if (len < offset) {
if (!alwaysCompute)
return false;
if (len == 0.0d) {
returnVal[0] = offset + nodeX;
returnVal[1] = nodeY;
return true;
}
}
returnVal[0] = (float) (((dX / len) * offset) + nodeX);
returnVal[1] = (float) (((dY / len) * offset) + nodeY);
return true;
}
}
/**
* Render node view with details, including custom graphics.
*/
@SuppressWarnings("rawtypes")
private static final void renderNodeHigh(final CyNetworkViewSnapshot netView,
final GraphGraphics grafx,
final View<CyNode> cyNode,
final float[] floatBuff1,
final double[] doubleBuff1,
final double[] doubleBuff2,
final NodeDetails nodeDetails,
final RenderDetailFlags flags,
final Set<VisualPropertyDependency<?>> dependencies) {
Shape nodeShape = null;
if ((floatBuff1[0] != floatBuff1[2]) && (floatBuff1[1] != floatBuff1[3])) {
// Compute visual attributes that do not depend on LOD.
final byte shape = nodeDetails.getShape(cyNode);
final Paint fillPaint = nodeDetails.getFillPaint(cyNode);
// Compute node border information.
final float borderWidth;
final Paint borderPaint;
Stroke borderStroke = null;
if (flags.not(LOD_NODE_BORDERS)) { // Not rendering borders.
borderWidth = 0.0f;
borderPaint = null;
} else { // Rendering node borders.
borderWidth = nodeDetails.getBorderWidth(cyNode);
borderStroke = nodeDetails.getBorderStroke(cyNode);
if (borderWidth == 0.0f)
borderPaint = null;
else
borderPaint = nodeDetails.getBorderPaint(cyNode);
}
// Draw the node.
nodeShape = grafx.drawNodeFull(shape, floatBuff1[0], floatBuff1[1], floatBuff1[2], floatBuff1[3],
fillPaint, borderWidth, borderStroke, borderPaint);
}
// Take care of custom graphic rendering.
if (flags.has(LOD_CUSTOM_GRAPHICS)) {
// draw any nested networks first
final TexturePaint nestedNetworkPaint = nodeDetails.getNestedNetworkTexturePaint(netView, cyNode);
if (nestedNetworkPaint != null) {
doubleBuff1[0] = floatBuff1[0];
doubleBuff1[1] = floatBuff1[1];
doubleBuff1[2] = floatBuff1[2];
doubleBuff1[3] = floatBuff1[3];
lemma_computeAnchor(Position.CENTER, doubleBuff1, doubleBuff2);
grafx.drawCustomGraphicImage(nestedNetworkPaint.getAnchorRect(), (float)doubleBuff2[0], (float)doubleBuff2[1], nestedNetworkPaint);
}
// draw custom graphics on top of nested networks
// don't allow our custom graphics to mutate while we iterate over them:
// synchronized (nodeDetails.customGraphicsLock(cyNode)) {
synchronized (nodeDetails) {
// This method should return CustomGraphics in rendering order:
final Map<VisualProperty<CyCustomGraphics>, CustomGraphicsInfo> cgMap = nodeDetails.getCustomGraphics(cyNode);
final List<CustomGraphicsInfo> infoList = new ArrayList<>(cgMap.values());
for (final CustomGraphicsInfo cgInfo : infoList) {
// MKTODO I guess there's no way around doing this? The charts need access to the underlying table model.
CyNetworkView netViewForCharts = netView.getMutableNetworkView();
View<CyNode> mutableNode = netView.getMutableNodeView(cyNode.getSUID());
if(mutableNode != null) {
List<CustomGraphicLayer> layers = cgInfo.createLayers(netViewForCharts, mutableNode, nodeDetails, dependencies);
for (CustomGraphicLayer layer : layers) {
float offsetVectorX = nodeDetails.graphicOffsetVectorX(cyNode);
float offsetVectorY = nodeDetails.graphicOffsetVectorY(cyNode);
doubleBuff1[0] = floatBuff1[0];
doubleBuff1[1] = floatBuff1[1];
doubleBuff1[2] = floatBuff1[2];
doubleBuff1[3] = floatBuff1[3];
lemma_computeAnchor(Position.CENTER, doubleBuff1, doubleBuff2);
float xOffset = (float) (doubleBuff2[0] + offsetVectorX);
float yOffset = (float) (doubleBuff2[1] + offsetVectorY);
nodeShape = createCustomGraphicsShape(nodeShape, layer, -xOffset, -yOffset);
grafx.drawCustomGraphicFull(netViewForCharts, mutableNode, nodeShape, layer, xOffset, yOffset);
}
}
}
}
}
}
private static Shape createCustomGraphicsShape(final Shape nodeShape, final CustomGraphicLayer layer,
float xOffset, float yOffset) {
final Rectangle2D nsb = nodeShape.getBounds2D();
final Rectangle2D cgb = layer.getBounds2D();
final AffineTransform xform = new AffineTransform();
xform.scale(cgb.getWidth() / nsb.getWidth(), cgb.getHeight() / nsb.getHeight());
xform.translate(xOffset, yOffset);
return xform.createTransformedShape(nodeShape);
}
}
| CYTOSCAPE-12762 Fix haystack edges sometimes shifting positions. | ding-impl/ding-presentation-impl/src/main/java/org/cytoscape/graph/render/stateful/GraphRenderer.java | CYTOSCAPE-12762 Fix haystack edges sometimes shifting positions. | <ide><path>ing-impl/ding-presentation-impl/src/main/java/org/cytoscape/graph/render/stateful/GraphRenderer.java
<ide>
<ide> final byte otherNodeShape = nodeDetails.getShape(otherCyNode);
<ide>
<del> // Compute node shapes, center positions, and extents.
<ide> final byte srcShape;
<del>
<del> // Compute node shapes, center positions, and extents.
<ide> final byte trgShape;
<ide> final float[] srcExtents;
<ide> final float[] trgExtents;
<add> final long srcSuid;
<add> final long trgSuid;
<add>
<ide> if (nodeSuid == sourceViewSUID) {
<ide> srcShape = nodeShape;
<ide> trgShape = otherNodeShape;
<ide> srcExtents = floatBuff1;
<ide> trgExtents = floatBuff2;
<del> } else { // node == graph.edgeTarget(edge).
<add> srcSuid = nodeSuid;
<add> trgSuid = otherNode;
<add> } else {
<ide> srcShape = otherNodeShape;
<ide> trgShape = nodeShape;
<ide> srcExtents = floatBuff2;
<ide> trgExtents = floatBuff1;
<add> srcSuid = otherNode;
<add> trgSuid = nodeSuid;
<ide> }
<ide>
<ide> // Compute visual attributes that do not depend on LOD.
<ide> if(haystack) {
<ide> float radiusModifier = edgeDetails.getHaystackRadius(edge);
<ide> if (!computeEdgeEndpointsHaystack(srcExtents, trgExtents, floatBuff3, floatBuff4,
<del> nodeSuid, otherNode, edgeSuid, haystackDataBuff, radiusModifier))
<add> srcSuid, trgSuid, edgeSuid, haystackDataBuff, radiusModifier))
<ide> continue;
<ide> }
<ide> else { |
|
Java | apache-2.0 | 695237be05181609e94d79dabc9029065b8752d4 | 0 | bazelbuild/bazel,katre/bazel,bazelbuild/bazel,katre/bazel,bazelbuild/bazel,bazelbuild/bazel,bazelbuild/bazel,katre/bazel,katre/bazel,katre/bazel,katre/bazel,bazelbuild/bazel | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.starlark;
import static com.google.devtools.build.lib.analysis.starlark.StarlarkRuleContext.checkPrivateAccess;
import static com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions.EXPERIMENTAL_SIBLING_REPOSITORY_LAYOUT;
import static com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions.INCOMPATIBLE_DISALLOW_SYMLINK_FILE_TO_DIR;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.ActionLookupKey;
import com.google.devtools.build.lib.actions.ActionRegistry;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.actions.CommandLine;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ParamFileInfo;
import com.google.devtools.build.lib.actions.ResourceSet;
import com.google.devtools.build.lib.actions.ResourceSetOrBuilder;
import com.google.devtools.build.lib.actions.RunfilesSupplier;
import com.google.devtools.build.lib.actions.UserExecException;
import com.google.devtools.build.lib.actions.extra.ExtraActionInfo;
import com.google.devtools.build.lib.actions.extra.SpawnInfo;
import com.google.devtools.build.lib.analysis.BashCommandConstructor;
import com.google.devtools.build.lib.analysis.CommandHelper;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.PseudoAction;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.ShToolchain;
import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
import com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.actions.StarlarkAction;
import com.google.devtools.build.lib.analysis.actions.Substitution;
import com.google.devtools.build.lib.analysis.actions.SymlinkAction;
import com.google.devtools.build.lib.analysis.actions.TemplateExpansionAction;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.collect.nestedset.Depset;
import com.google.devtools.build.lib.collect.nestedset.Depset.TypeException;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.ExecGroup;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.server.FailureDetails;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.Interrupted;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.SerializationConstant;
import com.google.devtools.build.lib.starlarkbuildapi.FileApi;
import com.google.devtools.build.lib.starlarkbuildapi.StarlarkActionFactoryApi;
import com.google.devtools.build.lib.starlarkbuildapi.TemplateDictApi;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.protobuf.GeneratedMessage;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Mutability;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.Sequence;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkCallable;
import net.starlark.java.eval.StarlarkFloat;
import net.starlark.java.eval.StarlarkFunction;
import net.starlark.java.eval.StarlarkInt;
import net.starlark.java.eval.StarlarkSemantics;
import net.starlark.java.eval.StarlarkThread;
/** Provides a Starlark interface for all action creation needs. */
public class StarlarkActionFactory implements StarlarkActionFactoryApi {
private final StarlarkRuleContext context;
/** Counter for actions.run_shell helper scripts. Every script must have a unique name. */
private int runShellOutputCounter = 0;
private static final ResourceSet DEFAULT_RESOURCE_SET = ResourceSet.createWithRamCpu(250, 1);
private static final Set<String> validResources =
new HashSet<>(Arrays.asList("cpu", "memory", "local_test"));
public StarlarkActionFactory(StarlarkRuleContext context) {
this.context = context;
}
ArtifactRoot newFileRoot() {
return context.isForAspect()
? getRuleContext().getBinDirectory()
: getRuleContext().getBinOrGenfilesDirectory();
}
/**
* Returns a {@link ActionRegistry} object to register actions using this action factory.
*
* @throws EvalException if actions cannot be registered with this object
*/
public ActionRegistry asActionRegistry(StarlarkActionFactory starlarkActionFactory)
throws EvalException {
validateActionCreation();
return new ActionRegistry() {
@Override
public void registerAction(ActionAnalysisMetadata action) {
getRuleContext().registerAction(action);
}
@Override
public ActionLookupKey getOwner() {
return starlarkActionFactory
.getActionConstructionContext()
.getAnalysisEnvironment()
.getOwner();
}
};
}
@Override
public Artifact declareFile(String filename, Object sibling) throws EvalException {
context.checkMutable("actions.declare_file");
RuleContext ruleContext = getRuleContext();
PathFragment fragment;
if (Starlark.NONE.equals(sibling)) {
fragment = ruleContext.getPackageDirectory().getRelative(PathFragment.create(filename));
} else {
PathFragment original =
((Artifact) sibling)
.getOutputDirRelativePath(
getSemantics().getBool(EXPERIMENTAL_SIBLING_REPOSITORY_LAYOUT));
fragment = original.replaceName(filename);
}
if (!fragment.startsWith(ruleContext.getPackageDirectory())) {
throw Starlark.errorf(
"the output artifact '%s' is not under package directory '%s' for target '%s'",
fragment, ruleContext.getPackageDirectory(), ruleContext.getLabel());
}
return ruleContext.getDerivedArtifact(fragment, newFileRoot());
}
@Override
public Artifact declareDirectory(String filename, Object sibling) throws EvalException {
context.checkMutable("actions.declare_directory");
RuleContext ruleContext = getRuleContext();
PathFragment fragment;
if (Starlark.NONE.equals(sibling)) {
fragment = ruleContext.getPackageDirectory().getRelative(PathFragment.create(filename));
} else {
PathFragment original =
((Artifact) sibling)
.getOutputDirRelativePath(
getSemantics().getBool(EXPERIMENTAL_SIBLING_REPOSITORY_LAYOUT));
fragment = original.replaceName(filename);
}
if (!fragment.startsWith(ruleContext.getPackageDirectory())) {
throw Starlark.errorf(
"the output directory '%s' is not under package directory '%s' for target '%s'",
fragment, ruleContext.getPackageDirectory(), ruleContext.getLabel());
}
Artifact result = ruleContext.getTreeArtifact(fragment, newFileRoot());
if (!result.isTreeArtifact()) {
throw Starlark.errorf(
"'%s' has already been declared as a regular file, not directory.", filename);
}
return result;
}
@Override
public Artifact declareSymlink(String filename, Object sibling) throws EvalException {
context.checkMutable("actions.declare_symlink");
RuleContext ruleContext = getRuleContext();
if (!ruleContext.getConfiguration().allowUnresolvedSymlinks()) {
throw Starlark.errorf(
"actions.declare_symlink() is not allowed; "
+ "use the --experimental_allow_unresolved_symlinks command line option");
}
Artifact result;
PathFragment rootRelativePath;
if (Starlark.NONE.equals(sibling)) {
rootRelativePath = ruleContext.getPackageDirectory().getRelative(filename);
} else {
PathFragment original =
((Artifact) sibling)
.getOutputDirRelativePath(
getSemantics().getBool(EXPERIMENTAL_SIBLING_REPOSITORY_LAYOUT));
rootRelativePath = original.replaceName(filename);
}
result =
ruleContext.getAnalysisEnvironment().getSymlinkArtifact(rootRelativePath, newFileRoot());
if (!result.isSymlink()) {
throw Starlark.errorf(
"'%s' has already been declared as something other than a symlink.", filename);
}
return result;
}
@Override
public void doNothing(String mnemonic, Object inputs) throws EvalException {
context.checkMutable("actions.do_nothing");
RuleContext ruleContext = getRuleContext();
NestedSet<Artifact> inputSet =
inputs instanceof Depset
? Depset.cast(inputs, Artifact.class, "inputs")
: NestedSetBuilder.<Artifact>compileOrder()
.addAll(Sequence.cast(inputs, Artifact.class, "inputs"))
.build();
Action action =
new PseudoAction<>(
UUID.nameUUIDFromBytes(
String.format("empty action %s", ruleContext.getLabel())
.getBytes(StandardCharsets.UTF_8)),
ruleContext.getActionOwner(),
inputSet,
ImmutableList.of(PseudoAction.getDummyOutput(ruleContext)),
mnemonic,
SPAWN_INFO,
SpawnInfo.newBuilder().build());
registerAction(action);
}
@SerializationConstant @AutoCodec.VisibleForSerialization
static final GeneratedMessage.GeneratedExtension<ExtraActionInfo, SpawnInfo> SPAWN_INFO =
SpawnInfo.spawnInfo;
@Override
public void symlink(
FileApi output,
Object /* Artifact or None */ targetFile,
Object /* String or None */ targetPath,
Boolean isExecutable,
Object /* String or None */ progressMessageUnchecked)
throws EvalException {
context.checkMutable("actions.symlink");
RuleContext ruleContext = getRuleContext();
if ((targetFile == Starlark.NONE) == (targetPath == Starlark.NONE)) {
throw Starlark.errorf("Exactly one of \"target_file\" or \"target_path\" is required");
}
Artifact outputArtifact = (Artifact) output;
String progressMessage =
(progressMessageUnchecked != Starlark.NONE)
? (String) progressMessageUnchecked
: "Creating symlink %{output}";
Action action;
if (targetFile != Starlark.NONE) {
Artifact inputArtifact = (Artifact) targetFile;
if (outputArtifact.isSymlink()) {
throw Starlark.errorf(
"symlink() with \"target_file\" param requires that \"output\" be declared as a "
+ "file or directory, not a symlink (did you mean to use declare_file() or "
+ "declare_directory() instead of declare_symlink()?)");
}
boolean inputOutputMismatch =
getSemantics().getBool(INCOMPATIBLE_DISALLOW_SYMLINK_FILE_TO_DIR)
? inputArtifact.isDirectory() != outputArtifact.isDirectory()
: !inputArtifact.isDirectory() && outputArtifact.isDirectory();
if (inputOutputMismatch) {
String inputType = inputArtifact.isDirectory() ? "directory" : "file";
String outputType = outputArtifact.isDirectory() ? "directory" : "file";
throw Starlark.errorf(
"symlink() with \"target_file\" %s param requires that \"output\" be declared as a %s "
+ "(did you mean to use declare_%s() instead of declare_%s()?)",
inputType, inputType, inputType, outputType);
}
if (isExecutable) {
if (outputArtifact.isTreeArtifact()) {
throw Starlark.errorf("symlink() with \"output\" directory param cannot be executable");
}
action =
SymlinkAction.toExecutable(
ruleContext.getActionOwner(), inputArtifact, outputArtifact, progressMessage);
} else {
action =
SymlinkAction.toArtifact(
ruleContext.getActionOwner(), inputArtifact, outputArtifact, progressMessage);
}
} else {
if (!ruleContext.getConfiguration().allowUnresolvedSymlinks()) {
throw Starlark.errorf(
"actions.symlink() to unresolved symlink is not allowed; "
+ "use the --experimental_allow_unresolved_symlinks command line option");
}
if (!outputArtifact.isSymlink()) {
throw Starlark.errorf(
"symlink() with \"target_path\" param requires that \"output\" be declared as a "
+ "symlink, not a file or directory (did you mean to use declare_symlink() instead "
+ "of declare_file() or declare_directory()?)");
}
if (isExecutable) {
throw Starlark.errorf("\"is_executable\" cannot be True when using \"target_path\"");
}
action =
UnresolvedSymlinkAction.create(
ruleContext.getActionOwner(), outputArtifact, (String) targetPath, progressMessage);
}
registerAction(action);
}
@Override
public void write(FileApi output, Object content, Boolean isExecutable) throws EvalException {
context.checkMutable("actions.write");
RuleContext ruleContext = getRuleContext();
final Action action;
if (content instanceof String) {
action =
FileWriteAction.create(ruleContext, (Artifact) output, (String) content, isExecutable);
} else if (content instanceof Args) {
Args args = (Args) content;
action =
new ParameterFileWriteAction(
ruleContext.getActionOwner(),
NestedSetBuilder.wrap(Order.STABLE_ORDER, args.getDirectoryArtifacts()),
(Artifact) output,
args.build(),
args.getParameterFileType());
} else {
throw new AssertionError("Unexpected type: " + content.getClass().getSimpleName());
}
registerAction(action);
}
@Override
public void run(
Sequence<?> outputs,
Object inputs,
Object unusedInputsList,
Object executableUnchecked,
Object toolsUnchecked,
Sequence<?> arguments,
Object mnemonicUnchecked,
Object progressMessage,
Boolean useDefaultShellEnv,
Object envUnchecked,
Object executionRequirementsUnchecked,
Object inputManifestsUnchecked,
Object execGroupUnchecked,
Object shadowedActionUnchecked,
Object resourceSetUnchecked)
throws EvalException {
context.checkMutable("actions.run");
StarlarkAction.Builder builder = new StarlarkAction.Builder();
buildCommandLine(builder, arguments);
if (executableUnchecked instanceof Artifact) {
Artifact executable = (Artifact) executableUnchecked;
FilesToRunProvider provider = context.getExecutableRunfiles(executable);
if (provider == null) {
builder.setExecutable(executable);
} else {
builder.setExecutable(provider);
}
} else if (executableUnchecked instanceof String) {
// Normalise if needed and then pass as a String; this keeps the reference when PathFragment
// is passed from native to Starlark
builder.setExecutableAsString(
PathFragment.create((String) executableUnchecked).getPathString());
} else if (executableUnchecked instanceof FilesToRunProvider) {
builder.setExecutable((FilesToRunProvider) executableUnchecked);
} else {
// Should have been verified by Starlark before this function is called
throw new IllegalStateException();
}
registerStarlarkAction(
outputs,
inputs,
unusedInputsList,
toolsUnchecked,
mnemonicUnchecked,
progressMessage,
useDefaultShellEnv,
envUnchecked,
executionRequirementsUnchecked,
inputManifestsUnchecked,
execGroupUnchecked,
shadowedActionUnchecked,
resourceSetUnchecked,
builder);
}
private void validateActionCreation() throws EvalException {
if (getRuleContext().getRule().isAnalysisTest()) {
throw Starlark.errorf(
"implementation function of a rule with "
+ "analysis_test=true may not register actions. Analysis test rules may only return "
+ "success/failure information via AnalysisTestResultInfo.");
}
}
/**
* Registers action in the context of this {@link StarlarkActionFactory}.
*
* <p>Use {@link #getActionConstructionContext()} to obtain the context required to create this
* action.
*/
public void registerAction(ActionAnalysisMetadata action) throws EvalException {
validateActionCreation();
getRuleContext().registerAction(action);
}
/**
* Returns information needed to construct actions that can be registered with {@link
* #registerAction}.
*/
public ActionConstructionContext getActionConstructionContext() {
return context.getRuleContext();
}
public RuleContext getRuleContext() {
return context.getRuleContext();
}
private StarlarkSemantics getSemantics() {
return context.getStarlarkSemantics();
}
private void verifyExecGroup(Object execGroupUnchecked, RuleContext ctx) throws EvalException {
String execGroup = (String) execGroupUnchecked;
if (!StarlarkExecGroupCollection.isValidGroupName(execGroup)
|| !ctx.hasToolchainContext(execGroup)) {
throw Starlark.errorf("Action declared for non-existent exec group '%s'.", execGroup);
}
}
private PlatformInfo getExecutionPlatform(Object execGroupUnchecked, RuleContext ctx)
throws EvalException {
if (execGroupUnchecked == Starlark.NONE) {
return ctx.getExecutionPlatform(ExecGroup.DEFAULT_EXEC_GROUP_NAME);
} else {
verifyExecGroup(execGroupUnchecked, ctx);
return ctx.getExecutionPlatform((String) execGroupUnchecked);
}
}
@Override
public void runShell(
Sequence<?> outputs,
Object inputs,
Object toolsUnchecked,
Sequence<?> arguments,
Object mnemonicUnchecked,
Object commandUnchecked,
Object progressMessage,
Boolean useDefaultShellEnv,
Object envUnchecked,
Object executionRequirementsUnchecked,
Object inputManifestsUnchecked,
Object execGroupUnchecked,
Object shadowedActionUnchecked,
Object resourceSetUnchecked)
throws EvalException {
context.checkMutable("actions.run_shell");
RuleContext ruleContext = getRuleContext();
StarlarkAction.Builder builder = new StarlarkAction.Builder();
buildCommandLine(builder, arguments);
if (commandUnchecked instanceof String) {
ImmutableMap<String, String> executionInfo =
ImmutableMap.copyOf(TargetUtils.getExecutionInfo(ruleContext.getRule()));
String helperScriptSuffix = String.format(".run_shell_%d.sh", runShellOutputCounter++);
String command = (String) commandUnchecked;
PathFragment shExecutable =
ShToolchain.getPathForPlatform(
ruleContext.getConfiguration(),
getExecutionPlatform(execGroupUnchecked, ruleContext));
BashCommandConstructor constructor =
CommandHelper.buildBashCommandConstructor(
executionInfo, shExecutable, helperScriptSuffix);
Artifact helperScript =
CommandHelper.commandHelperScriptMaybe(ruleContext, command, constructor);
if (helperScript == null) {
builder.setShellCommand(shExecutable, command);
} else {
builder.setShellCommand(shExecutable, helperScript.getExecPathString());
builder.addInput(helperScript);
FilesToRunProvider provider = context.getExecutableRunfiles(helperScript);
if (provider != null) {
builder.addTool(provider);
}
}
} else if (commandUnchecked instanceof Sequence) {
if (getSemantics().getBool(BuildLanguageOptions.INCOMPATIBLE_RUN_SHELL_COMMAND_STRING)) {
throw Starlark.errorf(
"'command' must be of type string. passing a sequence of strings as 'command'"
+ " is deprecated. To temporarily disable this check,"
+ " set --incompatible_run_shell_command_string=false.");
}
Sequence<?> commandList = (Sequence) commandUnchecked;
if (!arguments.isEmpty()) {
throw Starlark.errorf("'arguments' must be empty if 'command' is a sequence of strings");
}
List<String> command = Sequence.cast(commandList, String.class, "command");
builder.setShellCommand(command);
} else {
throw Starlark.errorf(
"expected string or list of strings for command instead of %s",
Starlark.type(commandUnchecked));
}
if (!arguments.isEmpty()) {
// When we use a shell command, add an empty argument before other arguments.
// e.g. bash -c "cmd" '' 'arg1' 'arg2'
// bash will use the empty argument as the value of $0 (which we don't care about).
// arg1 and arg2 will be $1 and $2, as a user expects.
builder.addExecutableArguments("");
}
registerStarlarkAction(
outputs,
inputs,
/*unusedInputsList=*/ Starlark.NONE,
toolsUnchecked,
mnemonicUnchecked,
progressMessage,
useDefaultShellEnv,
envUnchecked,
executionRequirementsUnchecked,
inputManifestsUnchecked,
execGroupUnchecked,
shadowedActionUnchecked,
resourceSetUnchecked,
builder);
}
private static void buildCommandLine(SpawnAction.Builder builder, Sequence<?> argumentsList)
throws EvalException {
List<String> stringArgs = new ArrayList<>();
for (Object value : argumentsList) {
if (value instanceof String) {
stringArgs.add((String) value);
} else if (value instanceof Args) {
if (!stringArgs.isEmpty()) {
builder.addCommandLine(CommandLine.of(stringArgs));
stringArgs = new ArrayList<>();
}
Args args = (Args) value;
ParamFileInfo paramFileInfo = args.getParamFileInfo();
builder.addCommandLine(args.build(), paramFileInfo);
} else {
throw Starlark.errorf(
"expected list of strings or ctx.actions.args() for arguments instead of %s",
Starlark.type(value));
}
}
if (!stringArgs.isEmpty()) {
builder.addCommandLine(CommandLine.of(stringArgs));
}
}
/**
* Setup for spawn actions common between {@link #run} and {@link #runShell}.
*
* <p>{@code builder} should have either executable or a command set.
*/
private void registerStarlarkAction(
Sequence<?> outputs,
Object inputs,
Object unusedInputsList,
Object toolsUnchecked,
Object mnemonicUnchecked,
Object progressMessage,
Boolean useDefaultShellEnv,
Object envUnchecked,
Object executionRequirementsUnchecked,
Object inputManifestsUnchecked,
Object execGroupUnchecked,
Object shadowedActionUnchecked,
Object resourceSetUnchecked,
StarlarkAction.Builder builder)
throws EvalException {
if (inputs instanceof Sequence) {
builder.addInputs(Sequence.cast(inputs, Artifact.class, "inputs"));
} else {
builder.addTransitiveInputs(Depset.cast(inputs, Artifact.class, "inputs"));
}
List<Artifact> outputArtifacts = Sequence.cast(outputs, Artifact.class, "outputs");
if (outputArtifacts.isEmpty()) {
throw Starlark.errorf("param 'outputs' may not be empty");
}
builder.addOutputs(outputArtifacts);
if (unusedInputsList != Starlark.NONE) {
if (unusedInputsList instanceof Artifact) {
builder.setUnusedInputsList(Optional.of((Artifact) unusedInputsList));
} else {
throw Starlark.errorf(
"expected value of type 'File' for a member of parameter 'unused_inputs_list' but got"
+ " %s instead",
Starlark.type(unusedInputsList));
}
}
if (toolsUnchecked != Starlark.UNBOUND) {
List<?> tools =
toolsUnchecked instanceof Sequence
? Sequence.cast(toolsUnchecked, Object.class, "tools")
: Depset.cast(toolsUnchecked, Object.class, "tools").toList();
for (Object toolUnchecked : tools) {
if (toolUnchecked instanceof Artifact) {
Artifact artifact = (Artifact) toolUnchecked;
builder.addTool(artifact);
FilesToRunProvider provider = context.getExecutableRunfiles(artifact);
if (provider != null) {
builder.addTool(provider);
}
} else if (toolUnchecked instanceof FilesToRunProvider) {
builder.addTool((FilesToRunProvider) toolUnchecked);
} else if (toolUnchecked instanceof Depset) {
try {
builder.addTransitiveTools(((Depset) toolUnchecked).getSet(Artifact.class));
} catch (TypeException e) {
throw Starlark.errorf(
"expected value of type 'File, FilesToRunProvider or Depset of Files' for a member "
+ "of parameter 'tools' but %s",
e.getMessage());
}
} else {
throw Starlark.errorf(
"expected value of type 'File, FilesToRunProvider or Depset of Files' for a member of"
+ " parameter 'tools' but got %s instead",
Starlark.type(toolUnchecked));
}
}
}
String mnemonic = getMnemonic(mnemonicUnchecked);
try {
builder.setMnemonic(mnemonic);
} catch (IllegalArgumentException e) {
throw Starlark.errorf("%s", e.getMessage());
}
if (envUnchecked != Starlark.NONE) {
builder.setEnvironment(
ImmutableMap.copyOf(Dict.cast(envUnchecked, String.class, String.class, "env")));
}
if (progressMessage != Starlark.NONE) {
builder.setProgressMessageFromStarlark((String) progressMessage);
}
if (Starlark.truth(useDefaultShellEnv)) {
builder.useDefaultShellEnvironment();
}
RuleContext ruleContext = getRuleContext();
ImmutableMap<String, String> executionInfo =
TargetUtils.getFilteredExecutionInfo(
executionRequirementsUnchecked,
ruleContext.getRule(),
getSemantics().getBool(BuildLanguageOptions.EXPERIMENTAL_ALLOW_TAGS_PROPAGATION));
builder.setExecutionInfo(executionInfo);
if (inputManifestsUnchecked != Starlark.NONE) {
for (RunfilesSupplier supplier :
Sequence.cast(inputManifestsUnchecked, RunfilesSupplier.class, "runfiles suppliers")) {
builder.addRunfilesSupplier(supplier);
}
}
if (execGroupUnchecked == Starlark.NONE) {
builder.setExecGroup(ExecGroup.DEFAULT_EXEC_GROUP_NAME);
} else {
verifyExecGroup(execGroupUnchecked, ruleContext);
builder.setExecGroup((String) execGroupUnchecked);
}
if (shadowedActionUnchecked != Starlark.NONE) {
builder.setShadowedAction(Optional.of((Action) shadowedActionUnchecked));
}
if (getSemantics().getBool(BuildLanguageOptions.EXPERIMENTAL_ACTION_RESOURCE_SET)
&& resourceSetUnchecked != Starlark.NONE) {
validateResourceSetBuilder(resourceSetUnchecked);
builder.setResources(
new StarlarkActionResourceSetBuilder(
(StarlarkCallable) resourceSetUnchecked, mnemonic, getSemantics()));
}
// Always register the action
registerAction(builder.build(ruleContext));
}
private static class StarlarkActionResourceSetBuilder implements ResourceSetOrBuilder {
private final StarlarkCallable fn;
private final String mnemonic;
private final StarlarkSemantics semantics;
public StarlarkActionResourceSetBuilder(
StarlarkCallable fn, String mnemonic, StarlarkSemantics semantics) {
this.fn = fn;
this.mnemonic = mnemonic;
this.semantics = semantics;
}
@Override
public ResourceSet buildResourceSet(OS os, int inputsSize) throws ExecException {
try (Mutability mu = Mutability.create("resource_set_builder_function")) {
StarlarkThread thread = new StarlarkThread(mu, semantics);
StarlarkInt inputInt = StarlarkInt.of(inputsSize);
Object response =
Starlark.call(
thread,
this.fn,
ImmutableList.of(os.getCanonicalName(), inputInt),
ImmutableMap.of());
Map<String, Object> resourceSetMapRaw =
Dict.cast(response, String.class, Object.class, "resource_set");
if (!validResources.containsAll(resourceSetMapRaw.keySet())) {
String message =
String.format(
"Illegal resource keys: (%s)",
Joiner.on(",").join(Sets.difference(resourceSetMapRaw.keySet(), validResources)));
throw new EvalException(message);
}
return ResourceSet.create(
getNumericOrDefault(resourceSetMapRaw, "memory", DEFAULT_RESOURCE_SET.getMemoryMb()),
getNumericOrDefault(resourceSetMapRaw, "cpu", DEFAULT_RESOURCE_SET.getCpuUsage()),
(int)
getNumericOrDefault(
resourceSetMapRaw,
"local_test",
(double) DEFAULT_RESOURCE_SET.getLocalTestCount()));
} catch (EvalException e) {
throw new UserExecException(
FailureDetail.newBuilder()
.setMessage(
String.format("Could not build resources for %s. %s", mnemonic, e.getMessage()))
.setStarlarkAction(
FailureDetails.StarlarkAction.newBuilder()
.setCode(FailureDetails.StarlarkAction.Code.STARLARK_ACTION_UNKNOWN)
.build())
.build());
} catch (InterruptedException e) {
throw new UserExecException(
FailureDetail.newBuilder()
.setMessage(e.getMessage())
.setInterrupted(
Interrupted.newBuilder().setCode(Interrupted.Code.INTERRUPTED).build())
.build());
}
}
private static double getNumericOrDefault(
Map<String, Object> resourceSetMap, String key, double defaultValue) throws EvalException {
if (!resourceSetMap.containsKey(key)) {
return defaultValue;
}
Object value = resourceSetMap.get(key);
if (value instanceof StarlarkInt) {
return ((StarlarkInt) value).toDouble();
}
if (value instanceof StarlarkFloat) {
return ((StarlarkFloat) value).toDouble();
}
throw new EvalException(
String.format(
"Illegal resource value type for key %s: got %s, want int or float",
key, Starlark.type(value)));
}
}
private static StarlarkCallable validateResourceSetBuilder(Object fn) throws EvalException {
if (!(fn instanceof StarlarkCallable)) {
throw Starlark.errorf(
"resource_set should be a Starlark-callable function, but got %s instead",
Starlark.type(fn));
}
if (fn instanceof StarlarkFunction) {
StarlarkFunction sfn = (StarlarkFunction) fn;
// Reject non-global functions, because arbitrary closures may cause large
// analysis-phase data structures to remain live into the execution phase.
// We require that the function is "global" as opposed to "not a closure"
// because a global function may be closure if it refers to load bindings.
// This unfortunately disallows such trivially safe non-global
// functions as "lambda x: x".
// See https://github.com/bazelbuild/bazel/issues/12701.
if (sfn.getModule().getGlobal(sfn.getName()) != sfn) {
throw Starlark.errorf(
"to avoid unintended retention of analysis data structures, "
+ "the resource_set function (declared at %s) must be declared "
+ "by a top-level def statement",
sfn.getLocation());
}
}
return (StarlarkCallable) fn;
}
private String getMnemonic(Object mnemonicUnchecked) {
String mnemonic = mnemonicUnchecked == Starlark.NONE ? "Action" : (String) mnemonicUnchecked;
if (getRuleContext().getConfiguration().getReservedActionMnemonics().contains(mnemonic)) {
mnemonic = mangleMnemonic(mnemonic);
}
return mnemonic;
}
private static String mangleMnemonic(String mnemonic) {
return mnemonic + "FromStarlark";
}
@Override
public void expandTemplate(
FileApi template,
FileApi output,
Dict<?, ?> substitutionsUnchecked,
Boolean executable,
/* TemplateDict */ Object computedSubstitutions)
throws EvalException {
context.checkMutable("actions.expand_template");
// We use a map to check for duplicate keys
ImmutableMap.Builder<String, Substitution> substitutionsBuilder = ImmutableMap.builder();
for (Map.Entry<String, String> substitution :
Dict.cast(substitutionsUnchecked, String.class, String.class, "substitutions").entrySet()) {
// Blaze calls ParserInput.fromLatin1 when reading BUILD files, which might
// contain UTF-8 encoded symbols as part of template substitution.
// As a quick fix, the substitution values are corrected before being passed on.
// In the long term, avoiding ParserInput.fromLatin would be a better approach.
substitutionsBuilder.put(
substitution.getKey(),
Substitution.of(substitution.getKey(), convertLatin1ToUtf8(substitution.getValue())));
}
if (!Starlark.UNBOUND.equals(computedSubstitutions)) {
for (Substitution substitution : ((TemplateDict) computedSubstitutions).getAll()) {
substitutionsBuilder.put(substitution.getKey(), substitution);
}
}
ImmutableMap<String, Substitution> substitutionMap;
try {
substitutionMap = substitutionsBuilder.buildOrThrow();
} catch (IllegalArgumentException e) {
// user added duplicate keys, report the error, but the stack trace is not of use
throw Starlark.errorf("%s", e.getMessage());
}
TemplateExpansionAction action =
new TemplateExpansionAction(
getRuleContext().getActionOwner(),
(Artifact) template,
(Artifact) output,
substitutionMap.values().asList(),
executable);
registerAction(action);
}
/**
* Returns the proper UTF-8 representation of a String that was erroneously read using Latin1.
*
* @param latin1 Input string
* @return The input string, UTF8 encoded
*/
private static String convertLatin1ToUtf8(String latin1) {
return new String(latin1.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
}
@Override
public Args args(StarlarkThread thread) {
return Args.newArgs(thread.mutability(), getSemantics());
}
@Override
public TemplateDictApi templateDict() {
return TemplateDict.newDict();
}
@Override
public FileApi createShareableArtifact(String path, Object artifactRoot, StarlarkThread thread)
throws EvalException {
checkPrivateAccess(thread);
ArtifactRoot root =
artifactRoot == Starlark.UNBOUND
? getRuleContext().getBinDirectory()
: (ArtifactRoot) artifactRoot;
return getRuleContext().getShareableArtifact(PathFragment.create(path), root);
}
@Override
public boolean isImmutable() {
return context.isImmutable();
}
@Override
public void repr(Printer printer) {
printer.append("actions for");
context.repr(printer);
}
}
| src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.starlark;
import static com.google.devtools.build.lib.analysis.starlark.StarlarkRuleContext.checkPrivateAccess;
import static com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions.EXPERIMENTAL_SIBLING_REPOSITORY_LAYOUT;
import static com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions.INCOMPATIBLE_DISALLOW_SYMLINK_FILE_TO_DIR;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.ActionLookupKey;
import com.google.devtools.build.lib.actions.ActionRegistry;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.actions.CommandLine;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ParamFileInfo;
import com.google.devtools.build.lib.actions.ResourceSet;
import com.google.devtools.build.lib.actions.ResourceSetOrBuilder;
import com.google.devtools.build.lib.actions.RunfilesSupplier;
import com.google.devtools.build.lib.actions.UserExecException;
import com.google.devtools.build.lib.actions.extra.ExtraActionInfo;
import com.google.devtools.build.lib.actions.extra.SpawnInfo;
import com.google.devtools.build.lib.analysis.BashCommandConstructor;
import com.google.devtools.build.lib.analysis.CommandHelper;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.PseudoAction;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.ShToolchain;
import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext;
import com.google.devtools.build.lib.analysis.actions.FileWriteAction;
import com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.actions.StarlarkAction;
import com.google.devtools.build.lib.analysis.actions.Substitution;
import com.google.devtools.build.lib.analysis.actions.SymlinkAction;
import com.google.devtools.build.lib.analysis.actions.TemplateExpansionAction;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.collect.nestedset.Depset;
import com.google.devtools.build.lib.collect.nestedset.Depset.TypeException;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.ExecGroup;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.server.FailureDetails;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.Interrupted;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.SerializationConstant;
import com.google.devtools.build.lib.starlarkbuildapi.FileApi;
import com.google.devtools.build.lib.starlarkbuildapi.StarlarkActionFactoryApi;
import com.google.devtools.build.lib.starlarkbuildapi.TemplateDictApi;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.protobuf.GeneratedMessage;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Mutability;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.Sequence;
import net.starlark.java.eval.Starlark;
import net.starlark.java.eval.StarlarkCallable;
import net.starlark.java.eval.StarlarkFloat;
import net.starlark.java.eval.StarlarkFunction;
import net.starlark.java.eval.StarlarkInt;
import net.starlark.java.eval.StarlarkSemantics;
import net.starlark.java.eval.StarlarkThread;
/** Provides a Starlark interface for all action creation needs. */
public class StarlarkActionFactory implements StarlarkActionFactoryApi {
private final StarlarkRuleContext context;
/** Counter for actions.run_shell helper scripts. Every script must have a unique name. */
private int runShellOutputCounter = 0;
private static final ResourceSet DEFAULT_RESOURCE_SET = ResourceSet.createWithRamCpu(250, 1);
private static final Set<String> validResources =
new HashSet<>(Arrays.asList("cpu", "memory", "local_test"));
public StarlarkActionFactory(StarlarkRuleContext context) {
this.context = context;
}
ArtifactRoot newFileRoot() {
return context.isForAspect()
? getRuleContext().getBinDirectory()
: getRuleContext().getBinOrGenfilesDirectory();
}
/**
* Returns a {@link ActionRegistry} object to register actions using this action factory.
*
* @throws EvalException if actions cannot be registered with this object
*/
public ActionRegistry asActionRegistry(StarlarkActionFactory starlarkActionFactory)
throws EvalException {
validateActionCreation();
return new ActionRegistry() {
@Override
public void registerAction(ActionAnalysisMetadata action) {
getRuleContext().registerAction(action);
}
@Override
public ActionLookupKey getOwner() {
return starlarkActionFactory
.getActionConstructionContext()
.getAnalysisEnvironment()
.getOwner();
}
};
}
@Override
public Artifact declareFile(String filename, Object sibling) throws EvalException {
context.checkMutable("actions.declare_file");
RuleContext ruleContext = getRuleContext();
PathFragment fragment;
if (Starlark.NONE.equals(sibling)) {
fragment = ruleContext.getPackageDirectory().getRelative(PathFragment.create(filename));
} else {
PathFragment original =
((Artifact) sibling)
.getOutputDirRelativePath(
getSemantics().getBool(EXPERIMENTAL_SIBLING_REPOSITORY_LAYOUT));
fragment = original.replaceName(filename);
}
if (!fragment.startsWith(ruleContext.getPackageDirectory())) {
throw Starlark.errorf(
"the output artifact '%s' is not under package directory '%s' for target '%s'",
fragment, ruleContext.getPackageDirectory(), ruleContext.getLabel());
}
return ruleContext.getDerivedArtifact(fragment, newFileRoot());
}
@Override
public Artifact declareDirectory(String filename, Object sibling) throws EvalException {
context.checkMutable("actions.declare_directory");
RuleContext ruleContext = getRuleContext();
PathFragment fragment;
if (Starlark.NONE.equals(sibling)) {
fragment = ruleContext.getPackageDirectory().getRelative(PathFragment.create(filename));
} else {
PathFragment original =
((Artifact) sibling)
.getOutputDirRelativePath(
getSemantics().getBool(EXPERIMENTAL_SIBLING_REPOSITORY_LAYOUT));
fragment = original.replaceName(filename);
}
if (!fragment.startsWith(ruleContext.getPackageDirectory())) {
throw Starlark.errorf(
"the output directory '%s' is not under package directory '%s' for target '%s'",
fragment, ruleContext.getPackageDirectory(), ruleContext.getLabel());
}
Artifact result = ruleContext.getTreeArtifact(fragment, newFileRoot());
if (!result.isTreeArtifact()) {
throw Starlark.errorf(
"'%s' has already been declared as a regular file, not directory.", filename);
}
return result;
}
@Override
public Artifact declareSymlink(String filename, Object sibling) throws EvalException {
context.checkMutable("actions.declare_symlink");
RuleContext ruleContext = getRuleContext();
if (!ruleContext.getConfiguration().allowUnresolvedSymlinks()) {
throw Starlark.errorf(
"actions.declare_symlink() is not allowed; "
+ "use the --experimental_allow_unresolved_symlinks command line option");
}
Artifact result;
PathFragment rootRelativePath;
if (Starlark.NONE.equals(sibling)) {
rootRelativePath = ruleContext.getPackageDirectory().getRelative(filename);
} else {
PathFragment original =
((Artifact) sibling)
.getOutputDirRelativePath(
getSemantics().getBool(EXPERIMENTAL_SIBLING_REPOSITORY_LAYOUT));
rootRelativePath = original.replaceName(filename);
}
result =
ruleContext.getAnalysisEnvironment().getSymlinkArtifact(rootRelativePath, newFileRoot());
if (!result.isSymlink()) {
throw Starlark.errorf(
"'%s' has already been declared as something other than a symlink.", filename);
}
return result;
}
@Override
public void doNothing(String mnemonic, Object inputs) throws EvalException {
context.checkMutable("actions.do_nothing");
RuleContext ruleContext = getRuleContext();
NestedSet<Artifact> inputSet =
inputs instanceof Depset
? Depset.cast(inputs, Artifact.class, "inputs")
: NestedSetBuilder.<Artifact>compileOrder()
.addAll(Sequence.cast(inputs, Artifact.class, "inputs"))
.build();
Action action =
new PseudoAction<>(
UUID.nameUUIDFromBytes(
String.format("empty action %s", ruleContext.getLabel())
.getBytes(StandardCharsets.UTF_8)),
ruleContext.getActionOwner(),
inputSet,
ImmutableList.of(PseudoAction.getDummyOutput(ruleContext)),
mnemonic,
SPAWN_INFO,
SpawnInfo.newBuilder().build());
registerAction(action);
}
@SerializationConstant @AutoCodec.VisibleForSerialization
static final GeneratedMessage.GeneratedExtension<ExtraActionInfo, SpawnInfo> SPAWN_INFO =
SpawnInfo.spawnInfo;
@Override
public void symlink(
FileApi output,
Object /* Artifact or None */ targetFile,
Object /* String or None */ targetPath,
Boolean isExecutable,
Object /* String or None */ progressMessageUnchecked)
throws EvalException {
context.checkMutable("actions.symlink");
RuleContext ruleContext = getRuleContext();
if ((targetFile == Starlark.NONE) == (targetPath == Starlark.NONE)) {
throw Starlark.errorf("Exactly one of \"target_file\" or \"target_path\" is required");
}
Artifact outputArtifact = (Artifact) output;
String progressMessage =
(progressMessageUnchecked != Starlark.NONE)
? (String) progressMessageUnchecked
: "Creating symlink " + outputArtifact.getExecPathString();
Action action;
if (targetFile != Starlark.NONE) {
Artifact inputArtifact = (Artifact) targetFile;
if (outputArtifact.isSymlink()) {
throw Starlark.errorf(
"symlink() with \"target_file\" param requires that \"output\" be declared as a "
+ "file or directory, not a symlink (did you mean to use declare_file() or "
+ "declare_directory() instead of declare_symlink()?)");
}
boolean inputOutputMismatch =
getSemantics().getBool(INCOMPATIBLE_DISALLOW_SYMLINK_FILE_TO_DIR)
? inputArtifact.isDirectory() != outputArtifact.isDirectory()
: !inputArtifact.isDirectory() && outputArtifact.isDirectory();
if (inputOutputMismatch) {
String inputType = inputArtifact.isDirectory() ? "directory" : "file";
String outputType = outputArtifact.isDirectory() ? "directory" : "file";
throw Starlark.errorf(
"symlink() with \"target_file\" %s param requires that \"output\" be declared as a %s "
+ "(did you mean to use declare_%s() instead of declare_%s()?)",
inputType, inputType, inputType, outputType);
}
if (isExecutable) {
if (outputArtifact.isTreeArtifact()) {
throw Starlark.errorf("symlink() with \"output\" directory param cannot be executable");
}
action =
SymlinkAction.toExecutable(
ruleContext.getActionOwner(), inputArtifact, outputArtifact, progressMessage);
} else {
action =
SymlinkAction.toArtifact(
ruleContext.getActionOwner(), inputArtifact, outputArtifact, progressMessage);
}
} else {
if (!ruleContext.getConfiguration().allowUnresolvedSymlinks()) {
throw Starlark.errorf(
"actions.symlink() to unresolved symlink is not allowed; "
+ "use the --experimental_allow_unresolved_symlinks command line option");
}
if (!outputArtifact.isSymlink()) {
throw Starlark.errorf(
"symlink() with \"target_path\" param requires that \"output\" be declared as a "
+ "symlink, not a file or directory (did you mean to use declare_symlink() instead "
+ "of declare_file() or declare_directory()?)");
}
if (isExecutable) {
throw Starlark.errorf("\"is_executable\" cannot be True when using \"target_path\"");
}
action =
UnresolvedSymlinkAction.create(
ruleContext.getActionOwner(), outputArtifact, (String) targetPath, progressMessage);
}
registerAction(action);
}
@Override
public void write(FileApi output, Object content, Boolean isExecutable) throws EvalException {
context.checkMutable("actions.write");
RuleContext ruleContext = getRuleContext();
final Action action;
if (content instanceof String) {
action =
FileWriteAction.create(ruleContext, (Artifact) output, (String) content, isExecutable);
} else if (content instanceof Args) {
Args args = (Args) content;
action =
new ParameterFileWriteAction(
ruleContext.getActionOwner(),
NestedSetBuilder.wrap(Order.STABLE_ORDER, args.getDirectoryArtifacts()),
(Artifact) output,
args.build(),
args.getParameterFileType());
} else {
throw new AssertionError("Unexpected type: " + content.getClass().getSimpleName());
}
registerAction(action);
}
@Override
public void run(
Sequence<?> outputs,
Object inputs,
Object unusedInputsList,
Object executableUnchecked,
Object toolsUnchecked,
Sequence<?> arguments,
Object mnemonicUnchecked,
Object progressMessage,
Boolean useDefaultShellEnv,
Object envUnchecked,
Object executionRequirementsUnchecked,
Object inputManifestsUnchecked,
Object execGroupUnchecked,
Object shadowedActionUnchecked,
Object resourceSetUnchecked)
throws EvalException {
context.checkMutable("actions.run");
StarlarkAction.Builder builder = new StarlarkAction.Builder();
buildCommandLine(builder, arguments);
if (executableUnchecked instanceof Artifact) {
Artifact executable = (Artifact) executableUnchecked;
FilesToRunProvider provider = context.getExecutableRunfiles(executable);
if (provider == null) {
builder.setExecutable(executable);
} else {
builder.setExecutable(provider);
}
} else if (executableUnchecked instanceof String) {
// Normalise if needed and then pass as a String; this keeps the reference when PathFragment
// is passed from native to Starlark
builder.setExecutableAsString(
PathFragment.create((String) executableUnchecked).getPathString());
} else if (executableUnchecked instanceof FilesToRunProvider) {
builder.setExecutable((FilesToRunProvider) executableUnchecked);
} else {
// Should have been verified by Starlark before this function is called
throw new IllegalStateException();
}
registerStarlarkAction(
outputs,
inputs,
unusedInputsList,
toolsUnchecked,
mnemonicUnchecked,
progressMessage,
useDefaultShellEnv,
envUnchecked,
executionRequirementsUnchecked,
inputManifestsUnchecked,
execGroupUnchecked,
shadowedActionUnchecked,
resourceSetUnchecked,
builder);
}
private void validateActionCreation() throws EvalException {
if (getRuleContext().getRule().isAnalysisTest()) {
throw Starlark.errorf(
"implementation function of a rule with "
+ "analysis_test=true may not register actions. Analysis test rules may only return "
+ "success/failure information via AnalysisTestResultInfo.");
}
}
/**
* Registers action in the context of this {@link StarlarkActionFactory}.
*
* <p>Use {@link #getActionConstructionContext()} to obtain the context required to create this
* action.
*/
public void registerAction(ActionAnalysisMetadata action) throws EvalException {
validateActionCreation();
getRuleContext().registerAction(action);
}
/**
* Returns information needed to construct actions that can be registered with {@link
* #registerAction}.
*/
public ActionConstructionContext getActionConstructionContext() {
return context.getRuleContext();
}
public RuleContext getRuleContext() {
return context.getRuleContext();
}
private StarlarkSemantics getSemantics() {
return context.getStarlarkSemantics();
}
private void verifyExecGroup(Object execGroupUnchecked, RuleContext ctx) throws EvalException {
String execGroup = (String) execGroupUnchecked;
if (!StarlarkExecGroupCollection.isValidGroupName(execGroup)
|| !ctx.hasToolchainContext(execGroup)) {
throw Starlark.errorf("Action declared for non-existent exec group '%s'.", execGroup);
}
}
private PlatformInfo getExecutionPlatform(Object execGroupUnchecked, RuleContext ctx)
throws EvalException {
if (execGroupUnchecked == Starlark.NONE) {
return ctx.getExecutionPlatform(ExecGroup.DEFAULT_EXEC_GROUP_NAME);
} else {
verifyExecGroup(execGroupUnchecked, ctx);
return ctx.getExecutionPlatform((String) execGroupUnchecked);
}
}
@Override
public void runShell(
Sequence<?> outputs,
Object inputs,
Object toolsUnchecked,
Sequence<?> arguments,
Object mnemonicUnchecked,
Object commandUnchecked,
Object progressMessage,
Boolean useDefaultShellEnv,
Object envUnchecked,
Object executionRequirementsUnchecked,
Object inputManifestsUnchecked,
Object execGroupUnchecked,
Object shadowedActionUnchecked,
Object resourceSetUnchecked)
throws EvalException {
context.checkMutable("actions.run_shell");
RuleContext ruleContext = getRuleContext();
StarlarkAction.Builder builder = new StarlarkAction.Builder();
buildCommandLine(builder, arguments);
if (commandUnchecked instanceof String) {
ImmutableMap<String, String> executionInfo =
ImmutableMap.copyOf(TargetUtils.getExecutionInfo(ruleContext.getRule()));
String helperScriptSuffix = String.format(".run_shell_%d.sh", runShellOutputCounter++);
String command = (String) commandUnchecked;
PathFragment shExecutable =
ShToolchain.getPathForPlatform(
ruleContext.getConfiguration(),
getExecutionPlatform(execGroupUnchecked, ruleContext));
BashCommandConstructor constructor =
CommandHelper.buildBashCommandConstructor(
executionInfo, shExecutable, helperScriptSuffix);
Artifact helperScript =
CommandHelper.commandHelperScriptMaybe(ruleContext, command, constructor);
if (helperScript == null) {
builder.setShellCommand(shExecutable, command);
} else {
builder.setShellCommand(shExecutable, helperScript.getExecPathString());
builder.addInput(helperScript);
FilesToRunProvider provider = context.getExecutableRunfiles(helperScript);
if (provider != null) {
builder.addTool(provider);
}
}
} else if (commandUnchecked instanceof Sequence) {
if (getSemantics().getBool(BuildLanguageOptions.INCOMPATIBLE_RUN_SHELL_COMMAND_STRING)) {
throw Starlark.errorf(
"'command' must be of type string. passing a sequence of strings as 'command'"
+ " is deprecated. To temporarily disable this check,"
+ " set --incompatible_run_shell_command_string=false.");
}
Sequence<?> commandList = (Sequence) commandUnchecked;
if (!arguments.isEmpty()) {
throw Starlark.errorf("'arguments' must be empty if 'command' is a sequence of strings");
}
List<String> command = Sequence.cast(commandList, String.class, "command");
builder.setShellCommand(command);
} else {
throw Starlark.errorf(
"expected string or list of strings for command instead of %s",
Starlark.type(commandUnchecked));
}
if (!arguments.isEmpty()) {
// When we use a shell command, add an empty argument before other arguments.
// e.g. bash -c "cmd" '' 'arg1' 'arg2'
// bash will use the empty argument as the value of $0 (which we don't care about).
// arg1 and arg2 will be $1 and $2, as a user expects.
builder.addExecutableArguments("");
}
registerStarlarkAction(
outputs,
inputs,
/*unusedInputsList=*/ Starlark.NONE,
toolsUnchecked,
mnemonicUnchecked,
progressMessage,
useDefaultShellEnv,
envUnchecked,
executionRequirementsUnchecked,
inputManifestsUnchecked,
execGroupUnchecked,
shadowedActionUnchecked,
resourceSetUnchecked,
builder);
}
private static void buildCommandLine(SpawnAction.Builder builder, Sequence<?> argumentsList)
throws EvalException {
List<String> stringArgs = new ArrayList<>();
for (Object value : argumentsList) {
if (value instanceof String) {
stringArgs.add((String) value);
} else if (value instanceof Args) {
if (!stringArgs.isEmpty()) {
builder.addCommandLine(CommandLine.of(stringArgs));
stringArgs = new ArrayList<>();
}
Args args = (Args) value;
ParamFileInfo paramFileInfo = args.getParamFileInfo();
builder.addCommandLine(args.build(), paramFileInfo);
} else {
throw Starlark.errorf(
"expected list of strings or ctx.actions.args() for arguments instead of %s",
Starlark.type(value));
}
}
if (!stringArgs.isEmpty()) {
builder.addCommandLine(CommandLine.of(stringArgs));
}
}
/**
* Setup for spawn actions common between {@link #run} and {@link #runShell}.
*
* <p>{@code builder} should have either executable or a command set.
*/
private void registerStarlarkAction(
Sequence<?> outputs,
Object inputs,
Object unusedInputsList,
Object toolsUnchecked,
Object mnemonicUnchecked,
Object progressMessage,
Boolean useDefaultShellEnv,
Object envUnchecked,
Object executionRequirementsUnchecked,
Object inputManifestsUnchecked,
Object execGroupUnchecked,
Object shadowedActionUnchecked,
Object resourceSetUnchecked,
StarlarkAction.Builder builder)
throws EvalException {
if (inputs instanceof Sequence) {
builder.addInputs(Sequence.cast(inputs, Artifact.class, "inputs"));
} else {
builder.addTransitiveInputs(Depset.cast(inputs, Artifact.class, "inputs"));
}
List<Artifact> outputArtifacts = Sequence.cast(outputs, Artifact.class, "outputs");
if (outputArtifacts.isEmpty()) {
throw Starlark.errorf("param 'outputs' may not be empty");
}
builder.addOutputs(outputArtifacts);
if (unusedInputsList != Starlark.NONE) {
if (unusedInputsList instanceof Artifact) {
builder.setUnusedInputsList(Optional.of((Artifact) unusedInputsList));
} else {
throw Starlark.errorf(
"expected value of type 'File' for a member of parameter 'unused_inputs_list' but got"
+ " %s instead",
Starlark.type(unusedInputsList));
}
}
if (toolsUnchecked != Starlark.UNBOUND) {
List<?> tools =
toolsUnchecked instanceof Sequence
? Sequence.cast(toolsUnchecked, Object.class, "tools")
: Depset.cast(toolsUnchecked, Object.class, "tools").toList();
for (Object toolUnchecked : tools) {
if (toolUnchecked instanceof Artifact) {
Artifact artifact = (Artifact) toolUnchecked;
builder.addTool(artifact);
FilesToRunProvider provider = context.getExecutableRunfiles(artifact);
if (provider != null) {
builder.addTool(provider);
}
} else if (toolUnchecked instanceof FilesToRunProvider) {
builder.addTool((FilesToRunProvider) toolUnchecked);
} else if (toolUnchecked instanceof Depset) {
try {
builder.addTransitiveTools(((Depset) toolUnchecked).getSet(Artifact.class));
} catch (TypeException e) {
throw Starlark.errorf(
"expected value of type 'File, FilesToRunProvider or Depset of Files' for a member "
+ "of parameter 'tools' but %s",
e.getMessage());
}
} else {
throw Starlark.errorf(
"expected value of type 'File, FilesToRunProvider or Depset of Files' for a member of"
+ " parameter 'tools' but got %s instead",
Starlark.type(toolUnchecked));
}
}
}
String mnemonic = getMnemonic(mnemonicUnchecked);
try {
builder.setMnemonic(mnemonic);
} catch (IllegalArgumentException e) {
throw Starlark.errorf("%s", e.getMessage());
}
if (envUnchecked != Starlark.NONE) {
builder.setEnvironment(
ImmutableMap.copyOf(Dict.cast(envUnchecked, String.class, String.class, "env")));
}
if (progressMessage != Starlark.NONE) {
builder.setProgressMessageFromStarlark((String) progressMessage);
}
if (Starlark.truth(useDefaultShellEnv)) {
builder.useDefaultShellEnvironment();
}
RuleContext ruleContext = getRuleContext();
ImmutableMap<String, String> executionInfo =
TargetUtils.getFilteredExecutionInfo(
executionRequirementsUnchecked,
ruleContext.getRule(),
getSemantics().getBool(BuildLanguageOptions.EXPERIMENTAL_ALLOW_TAGS_PROPAGATION));
builder.setExecutionInfo(executionInfo);
if (inputManifestsUnchecked != Starlark.NONE) {
for (RunfilesSupplier supplier :
Sequence.cast(inputManifestsUnchecked, RunfilesSupplier.class, "runfiles suppliers")) {
builder.addRunfilesSupplier(supplier);
}
}
if (execGroupUnchecked == Starlark.NONE) {
builder.setExecGroup(ExecGroup.DEFAULT_EXEC_GROUP_NAME);
} else {
verifyExecGroup(execGroupUnchecked, ruleContext);
builder.setExecGroup((String) execGroupUnchecked);
}
if (shadowedActionUnchecked != Starlark.NONE) {
builder.setShadowedAction(Optional.of((Action) shadowedActionUnchecked));
}
if (getSemantics().getBool(BuildLanguageOptions.EXPERIMENTAL_ACTION_RESOURCE_SET)
&& resourceSetUnchecked != Starlark.NONE) {
validateResourceSetBuilder(resourceSetUnchecked);
builder.setResources(
new StarlarkActionResourceSetBuilder(
(StarlarkCallable) resourceSetUnchecked, mnemonic, getSemantics()));
}
// Always register the action
registerAction(builder.build(ruleContext));
}
private static class StarlarkActionResourceSetBuilder implements ResourceSetOrBuilder {
private final StarlarkCallable fn;
private final String mnemonic;
private final StarlarkSemantics semantics;
public StarlarkActionResourceSetBuilder(
StarlarkCallable fn, String mnemonic, StarlarkSemantics semantics) {
this.fn = fn;
this.mnemonic = mnemonic;
this.semantics = semantics;
}
@Override
public ResourceSet buildResourceSet(OS os, int inputsSize) throws ExecException {
try (Mutability mu = Mutability.create("resource_set_builder_function")) {
StarlarkThread thread = new StarlarkThread(mu, semantics);
StarlarkInt inputInt = StarlarkInt.of(inputsSize);
Object response =
Starlark.call(
thread,
this.fn,
ImmutableList.of(os.getCanonicalName(), inputInt),
ImmutableMap.of());
Map<String, Object> resourceSetMapRaw =
Dict.cast(response, String.class, Object.class, "resource_set");
if (!validResources.containsAll(resourceSetMapRaw.keySet())) {
String message =
String.format(
"Illegal resource keys: (%s)",
Joiner.on(",").join(Sets.difference(resourceSetMapRaw.keySet(), validResources)));
throw new EvalException(message);
}
return ResourceSet.create(
getNumericOrDefault(resourceSetMapRaw, "memory", DEFAULT_RESOURCE_SET.getMemoryMb()),
getNumericOrDefault(resourceSetMapRaw, "cpu", DEFAULT_RESOURCE_SET.getCpuUsage()),
(int)
getNumericOrDefault(
resourceSetMapRaw,
"local_test",
(double) DEFAULT_RESOURCE_SET.getLocalTestCount()));
} catch (EvalException e) {
throw new UserExecException(
FailureDetail.newBuilder()
.setMessage(
String.format("Could not build resources for %s. %s", mnemonic, e.getMessage()))
.setStarlarkAction(
FailureDetails.StarlarkAction.newBuilder()
.setCode(FailureDetails.StarlarkAction.Code.STARLARK_ACTION_UNKNOWN)
.build())
.build());
} catch (InterruptedException e) {
throw new UserExecException(
FailureDetail.newBuilder()
.setMessage(e.getMessage())
.setInterrupted(
Interrupted.newBuilder().setCode(Interrupted.Code.INTERRUPTED).build())
.build());
}
}
private static double getNumericOrDefault(
Map<String, Object> resourceSetMap, String key, double defaultValue) throws EvalException {
if (!resourceSetMap.containsKey(key)) {
return defaultValue;
}
Object value = resourceSetMap.get(key);
if (value instanceof StarlarkInt) {
return ((StarlarkInt) value).toDouble();
}
if (value instanceof StarlarkFloat) {
return ((StarlarkFloat) value).toDouble();
}
throw new EvalException(
String.format(
"Illegal resource value type for key %s: got %s, want int or float",
key, Starlark.type(value)));
}
}
private static StarlarkCallable validateResourceSetBuilder(Object fn) throws EvalException {
if (!(fn instanceof StarlarkCallable)) {
throw Starlark.errorf(
"resource_set should be a Starlark-callable function, but got %s instead",
Starlark.type(fn));
}
if (fn instanceof StarlarkFunction) {
StarlarkFunction sfn = (StarlarkFunction) fn;
// Reject non-global functions, because arbitrary closures may cause large
// analysis-phase data structures to remain live into the execution phase.
// We require that the function is "global" as opposed to "not a closure"
// because a global function may be closure if it refers to load bindings.
// This unfortunately disallows such trivially safe non-global
// functions as "lambda x: x".
// See https://github.com/bazelbuild/bazel/issues/12701.
if (sfn.getModule().getGlobal(sfn.getName()) != sfn) {
throw Starlark.errorf(
"to avoid unintended retention of analysis data structures, "
+ "the resource_set function (declared at %s) must be declared "
+ "by a top-level def statement",
sfn.getLocation());
}
}
return (StarlarkCallable) fn;
}
private String getMnemonic(Object mnemonicUnchecked) {
String mnemonic = mnemonicUnchecked == Starlark.NONE ? "Action" : (String) mnemonicUnchecked;
if (getRuleContext().getConfiguration().getReservedActionMnemonics().contains(mnemonic)) {
mnemonic = mangleMnemonic(mnemonic);
}
return mnemonic;
}
private static String mangleMnemonic(String mnemonic) {
return mnemonic + "FromStarlark";
}
@Override
public void expandTemplate(
FileApi template,
FileApi output,
Dict<?, ?> substitutionsUnchecked,
Boolean executable,
/* TemplateDict */ Object computedSubstitutions)
throws EvalException {
context.checkMutable("actions.expand_template");
// We use a map to check for duplicate keys
ImmutableMap.Builder<String, Substitution> substitutionsBuilder = ImmutableMap.builder();
for (Map.Entry<String, String> substitution :
Dict.cast(substitutionsUnchecked, String.class, String.class, "substitutions").entrySet()) {
// Blaze calls ParserInput.fromLatin1 when reading BUILD files, which might
// contain UTF-8 encoded symbols as part of template substitution.
// As a quick fix, the substitution values are corrected before being passed on.
// In the long term, avoiding ParserInput.fromLatin would be a better approach.
substitutionsBuilder.put(
substitution.getKey(),
Substitution.of(substitution.getKey(), convertLatin1ToUtf8(substitution.getValue())));
}
if (!Starlark.UNBOUND.equals(computedSubstitutions)) {
for (Substitution substitution : ((TemplateDict) computedSubstitutions).getAll()) {
substitutionsBuilder.put(substitution.getKey(), substitution);
}
}
ImmutableMap<String, Substitution> substitutionMap;
try {
substitutionMap = substitutionsBuilder.buildOrThrow();
} catch (IllegalArgumentException e) {
// user added duplicate keys, report the error, but the stack trace is not of use
throw Starlark.errorf("%s", e.getMessage());
}
TemplateExpansionAction action =
new TemplateExpansionAction(
getRuleContext().getActionOwner(),
(Artifact) template,
(Artifact) output,
substitutionMap.values().asList(),
executable);
registerAction(action);
}
/**
* Returns the proper UTF-8 representation of a String that was erroneously read using Latin1.
*
* @param latin1 Input string
* @return The input string, UTF8 encoded
*/
private static String convertLatin1ToUtf8(String latin1) {
return new String(latin1.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
}
@Override
public Args args(StarlarkThread thread) {
return Args.newArgs(thread.mutability(), getSemantics());
}
@Override
public TemplateDictApi templateDict() {
return TemplateDict.newDict();
}
@Override
public FileApi createShareableArtifact(String path, Object artifactRoot, StarlarkThread thread)
throws EvalException {
checkPrivateAccess(thread);
ArtifactRoot root =
artifactRoot == Starlark.UNBOUND
? getRuleContext().getBinDirectory()
: (ArtifactRoot) artifactRoot;
return getRuleContext().getShareableArtifact(PathFragment.create(path), root);
}
@Override
public boolean isImmutable() {
return context.isImmutable();
}
@Override
public void repr(Printer printer) {
printer.append("actions for");
context.repr(printer);
}
}
| Use progress message placeholder to avoid a string allocation.
PiperOrigin-RevId: 485880574
Change-Id: I43ddb91a13185821413a171bb51da95b8154e73f
| src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java | Use progress message placeholder to avoid a string allocation. | <ide><path>rc/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java
<ide> String progressMessage =
<ide> (progressMessageUnchecked != Starlark.NONE)
<ide> ? (String) progressMessageUnchecked
<del> : "Creating symlink " + outputArtifact.getExecPathString();
<add> : "Creating symlink %{output}";
<ide>
<ide> Action action;
<ide> if (targetFile != Starlark.NONE) { |
|
Java | apache-2.0 | error: pathspec 'copy-list-with-random-pointer.java' did not match any file(s) known to git
| 29dbaa4f4a613c2368bad903bc7ffcd78221711f | 1 | andrewlxia/practice | /**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode p = head;
if (p == null) {
return null;
}
// make copies and chain them interleavely with original node
while(p != null) {
RandomListNode temp = new RandomListNode(p.label);
temp.next = p.next;
temp.random = p.random;
p.next = temp;
p = p.next.next;
}
//update random pointer of new nodes
p = head;
while(p != null) {
p = p.next;
if(p.random != null) {
p.random = p.random.next;
}
p = p.next;
}
// split to two lists
p = head;
RandomListNode newList = p.next;
RandomListNode q;
while(p != null) {
q = p.next;
p.next = q.next;
p = p.next;
if (q.next != null) {
q.next = q.next.next;
}
}
return newList;
}
}
| copy-list-with-random-pointer.java | Create copy-list-with-random-pointer.java | copy-list-with-random-pointer.java | Create copy-list-with-random-pointer.java | <ide><path>opy-list-with-random-pointer.java
<add>/**
<add> * Definition for singly-linked list with a random pointer.
<add> * class RandomListNode {
<add> * int label;
<add> * RandomListNode next, random;
<add> * RandomListNode(int x) { this.label = x; }
<add> * };
<add> */
<add>public class Solution {
<add> public RandomListNode copyRandomList(RandomListNode head) {
<add> RandomListNode p = head;
<add> if (p == null) {
<add> return null;
<add> }
<add>
<add> // make copies and chain them interleavely with original node
<add> while(p != null) {
<add> RandomListNode temp = new RandomListNode(p.label);
<add> temp.next = p.next;
<add> temp.random = p.random;
<add> p.next = temp;
<add> p = p.next.next;
<add> }
<add>
<add> //update random pointer of new nodes
<add> p = head;
<add> while(p != null) {
<add> p = p.next;
<add> if(p.random != null) {
<add> p.random = p.random.next;
<add> }
<add> p = p.next;
<add> }
<add>
<add> // split to two lists
<add> p = head;
<add> RandomListNode newList = p.next;
<add> RandomListNode q;
<add> while(p != null) {
<add> q = p.next;
<add> p.next = q.next;
<add> p = p.next;
<add> if (q.next != null) {
<add> q.next = q.next.next;
<add> }
<add> }
<add>
<add> return newList;
<add> }
<add>} |
|
Java | mit | 6a9b89ee39522c5189c26277f48c9de94570a7f5 | 0 | Vlatombe/git-plugin,Deveo/git-plugin,recena/git-plugin,pauxus/git-plugin,martinda/git-plugin,Deveo/git-plugin,jenkinsci/git-plugin,jenkinsci/git-plugin,jacob-keller/git-plugin,jacob-keller/git-plugin,Deveo/git-plugin,recena/git-plugin,v1v/git-plugin,kzantow/git-plugin,v1v/git-plugin,mklein0/git-plugin,pauxus/git-plugin,jacob-keller/git-plugin,ndeloof/git-plugin,kzantow/git-plugin,Vlatombe/git-plugin,ndeloof/git-plugin,jenkinsci/git-plugin,MarkEWaite/git-plugin,MarkEWaite/git-plugin,MarkEWaite/git-plugin,mklein0/git-plugin,martinda/git-plugin,mlgiroux/git-plugin,recena/git-plugin,martinda/git-plugin,jenkinsci/git-plugin,pauxus/git-plugin,v1v/git-plugin,mlgiroux/git-plugin,mlgiroux/git-plugin,Vlatombe/git-plugin,kzantow/git-plugin,MarkEWaite/git-plugin,mklein0/git-plugin,ndeloof/git-plugin | package hudson.plugins.git.util;
import hudson.model.Result;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.Revision;
import org.eclipse.jgit.lib.ObjectId;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.IOException;
import java.io.Serializable;
/**
* Remembers which build built which {@link Revision}.
*
* @see BuildData#buildsByBranchName
*/
@ExportedBean(defaultVisibility = 999)
public class Build implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
/**
* Revision in the repository marked as built.
*
* <p>
* This field is used to avoid doing the same build twice, by (normally) recording the commit in the upstream repository
* that initiated the build.
*
* <p>
* For simple use cases, this value is normally the same as {@link #revision}. Where this gets different is when
* a revision to checkout is decorated and differs from the commit found in the repository (for example, a merge
* before a build.) In such a situation, we need to remember the commit that came from the upstream so that
* future polling and build will not attempt to do another build from the same upstream commit.
*
* <p>
* In some other kind of speculative merging, such as github pull request build, this field should point
* to the same value as {@link #revision}, as we want to be able to build two pull requests rooted at the same
* commit in the base repository.
*/
public Revision marked;
/**
* Revision that was actually built.
*
* <p>
* This points to the commit that was checked out to the workspace when {@link GitSCM#checkout} left.
*/
public Revision revision;
public int hudsonBuildNumber;
public Result hudsonBuildResult;
// TODO: We don't currently store the result correctly.
public Build(Revision marked, Revision revision, int buildNumber, Result result) {
this.marked = marked;
this.revision = revision;
this.hudsonBuildNumber = buildNumber;
this.hudsonBuildResult = result;
}
public Build(Revision revision, int buildNumber, Result result) {
this(revision,revision,buildNumber,result);
}
public ObjectId getSHA1() {
return revision.getSha1();
}
@Exported
public Revision getRevision() {
return revision;
}
@Exported
public Revision getMarked() {
return marked;
}
@Exported
public int getBuildNumber() {
return hudsonBuildNumber;
}
@Exported
public Result getBuildResult() {
return hudsonBuildResult;
}
public @Override String toString() {
return "Build #" + hudsonBuildNumber + " of " + revision.toString();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Build)) {
return false;
} else {
Build otherBuild = (Build) o;
if (otherBuild.hudsonBuildNumber == this.hudsonBuildNumber
&& otherBuild.revision == this.revision
&& otherBuild.marked == this.marked) {
return true;
} else {
return false;
}
}
}
@Override
public Build clone() {
Build clone;
try {
clone = (Build) super.clone();
}
catch (CloneNotSupportedException e) {
throw new RuntimeException("Error cloning Build", e);
}
if (revision != null)
clone.revision = revision.clone();
if (marked != null)
clone.marked = marked.clone();
return clone;
}
public boolean isFor(String sha1) {
if (revision!=null && revision.getSha1String().startsWith(sha1)) return true;
return false;
}
public Object readResolve() throws IOException {
if (marked==null) // this field was introduced later than 'revision'
marked = revision;
return this;
}
} | src/main/java/hudson/plugins/git/util/Build.java | package hudson.plugins.git.util;
import hudson.model.Result;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.Revision;
import org.eclipse.jgit.lib.ObjectId;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.IOException;
import java.io.Serializable;
/**
* Remembers which build built which {@link Revision}.
*
* @see BuildData#buildsByBranchName
*/
@ExportedBean(defaultVisibility = 999)
public class Build implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
/**
* Revision in the repository marked as built.
*
* <p>
* This field is used to avoid doing the same build twice, by (normally) recording the commit in the upstream repository
* that initiated the build.
*
* <p>
* For simple use cases, this value is normally the same as {@link #revision}. Where this gets different is when
* a revision to checkout is decorated and differs from the commit found in the repository (for example, a merge
* before a build.) In such a situation, we need to remember the commit that came from the upstream so that
* future polling and build will not attempt to do another build from the same upstream commit.
*
* <p>
* In some other kind of speculative merging, such as github pull request build, this field should point
* to the same value as {@link #revision}, as we want to be able to build two pull requests rooted at the same
* commit in the base repository.
*/
public Revision marked;
/**
* Revision that was actually built.
*
* <p>
* This points to the commit that was checked out to the workspace when {@link GitSCM#checkout} left.
*/
public Revision revision;
public int hudsonBuildNumber;
public Result hudsonBuildResult;
// TODO: We don't currently store the result correctly.
public Build(Revision marked, Revision revision, int buildNumber, Result result) {
this.marked = marked;
this.revision = revision;
this.hudsonBuildNumber = buildNumber;
this.hudsonBuildResult = result;
}
public Build(Revision revision, int buildNumber, Result result) {
this(revision,revision,buildNumber,result);
}
public ObjectId getSHA1() {
return revision.getSha1();
}
@Exported
public Revision getRevision() {
return revision;
}
@Exported
public Revision getMarked() {
return marked;
}
@Exported
public int getBuildNumber() {
return hudsonBuildNumber;
}
@Exported
public Result getBuildResult() {
return hudsonBuildResult;
}
public @Override String toString() {
return "Build #" + hudsonBuildNumber + " of " + revision.toString();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Build)) {
return false;
} else {
Build otherBuild = (Build) o;
if (otherBuild.hudsonBuildNumber == this.hudsonBuildNumber
&& otherBuild.revision.equals(this.revision)) {
return true;
} else {
return false;
}
}
}
@Override
public Build clone() {
Build clone;
try {
clone = (Build) super.clone();
}
catch (CloneNotSupportedException e) {
throw new RuntimeException("Error cloning Build", e);
}
if (revision != null)
clone.revision = revision.clone();
if (marked != null)
clone.marked = marked.clone();
return clone;
}
public boolean isFor(String sha1) {
if (revision!=null && revision.getSha1String().startsWith(sha1)) return true;
return false;
}
public Object readResolve() throws IOException {
if (marked==null) // this field was introduced later than 'revision'
marked = revision;
return this;
}
} | Adding marked to Build.equals.
Also switched to == rather than .equals for comparing Revisions there,
to handle null case.
| src/main/java/hudson/plugins/git/util/Build.java | Adding marked to Build.equals. | <ide><path>rc/main/java/hudson/plugins/git/util/Build.java
<ide> } else {
<ide> Build otherBuild = (Build) o;
<ide> if (otherBuild.hudsonBuildNumber == this.hudsonBuildNumber
<del> && otherBuild.revision.equals(this.revision)) {
<add> && otherBuild.revision == this.revision
<add> && otherBuild.marked == this.marked) {
<ide> return true;
<ide> } else {
<ide> return false; |
|
Java | apache-2.0 | c8d8f75bc66f705dda2d16bb6a4103ebd51dd944 | 0 | Qi4j/qi4j-sdk,apache/zest-qi4j,Qi4j/qi4j-sdk,Qi4j/qi4j-sdk,apache/zest-qi4j,apache/zest-qi4j,Qi4j/qi4j-sdk,apache/zest-qi4j,apache/zest-qi4j,Qi4j/qi4j-sdk | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package org.apache.polygene.bootstrap;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import org.apache.polygene.api.activation.ActivationException;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.service.importer.InstanceImporter;
import org.apache.polygene.api.service.importer.NewObjectImporter;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.ApplicationDescriptor;
import org.apache.polygene.api.structure.Module;
@SuppressWarnings( { "unused", "ConstantConditionalExpression", "MethodNameSameAsClassName" } )
public class DocumentationSupport
{
public static Predicate<ObjectAssembly> hasMyTypeSpecification =
item -> item.types().anyMatch( type -> type.equals( String.class ) );
public static class declarations
{
static class MyObject {}
interface MyTransient {}
interface MyValue {}
interface MyEntity {}
class MyService {}
void declaration()
{
Assembler objects =
// START SNIPPET: objects
( ModuleAssembly module ) -> module.objects( MyObject.class ).visibleIn( Visibility.layer )
// END SNIPPET: objects
;
Assembler transients =
// START SNIPPET: transients
( ModuleAssembly module ) -> module.transients( MyTransient.class ).visibleIn( Visibility.layer )
// END SNIPPET: transients
;
Assembler values =
// START SNIPPET: values
( ModuleAssembly module ) -> module.values( MyValue.class ).visibleIn( Visibility.layer )
// END SNIPPET: values
;
Assembler entities =
// START SNIPPET: entities
( ModuleAssembly module ) -> module.entities( MyEntity.class ).visibleIn( Visibility.layer )
// END SNIPPET: entities
;
Assembler services =
// START SNIPPET: services
( ModuleAssembly module ) -> module.services( MyService.class ).visibleIn( Visibility.layer )
// END SNIPPET: services
;
Assembler taggedServices =
// START SNIPPET: tagged-services
( ModuleAssembly module ) -> module.services( MyService.class ).taggedWith( "foo", "bar" )
// END SNIPPET: tagged-services
;
List<Assembler> importedServices = Arrays.asList(
// START SNIPPET: imported-services
( ModuleAssembly module ) -> module.importedServices( MyService.class )
.importedBy( InstanceImporter.class )
.setMetaInfo( new MyService() ),
// OR
( ModuleAssembly module ) -> {
module.objects( MyService.class );
module.importedServices( MyService.class ).importedBy( NewObjectImporter.class );
}
// END SNIPPET: imported-services
);
}
}
static class defaultPropertyValues
{
interface MyValue
{
Property<String> foo();
}
interface MyEntity
{
Property<String> cathedral();
}
void defaultPropertyValues()
{
Assembler assembler =
// START SNIPPET: properties-defaults
( ModuleAssembly module ) -> {
module.values( MyValue.class );
MyValue myValueDefaults = module.forMixin( MyValue.class ).declareDefaults();
myValueDefaults.foo().set( "bar" );
module.entities( MyEntity.class );
MyEntity myEntityDefaults = module.forMixin( MyEntity.class ).declareDefaults();
myEntityDefaults.cathedral().set( "bazar" );
}
// END SNIPPET: properties-defaults
;
}
}
public static class singleton
{
interface MyService {}
interface Stuff {}
void singleton()
throws ActivationException, AssemblyException
{
// START SNIPPET: singleton
SingletonAssembler assembler = new SingletonAssembler(
module -> {
module.services( MyService.class ).identifiedBy( "Foo" );
module.services( MyService.class ).identifiedBy( "Bar" );
module.objects( Stuff.class );
}
);
Module module = assembler.module();
Stuff stuff = module.newObject( Stuff.class );
// END SNIPPET: singleton
}
}
public static class pancake
{
public static class LoginAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class MenuAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class PerspectivesAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class ViewsAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class ReportingAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class PdfAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class BookkeepingAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class CashFlowAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class BalanceSheetAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class PricingAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class ProductAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
private static Energy4Java polygene;
// START SNIPPET: pancake
public static void main( String[] args )
throws Exception
{
polygene = new Energy4Java();
Assembler[][][] assemblers = new Assembler[][][] {
{ // View Layer
{ // Login Module
new LoginAssembler()
// :
},
{ // Main Workbench Module
new MenuAssembler(),
new PerspectivesAssembler(),
new ViewsAssembler()
// :
},
{ // Printing Module
new ReportingAssembler(),
new PdfAssembler()
// :
}
},
{ // Application Layer
{ // Accounting Module
new BookkeepingAssembler(),
new CashFlowAssembler(),
new BalanceSheetAssembler()
// :
},
{ // Inventory Module
new PricingAssembler(),
new ProductAssembler()
// :
}
},
{ // Domain Layer
// :
},
{ // Infrastructure Layer
// :
}
};
ApplicationDescriptor model = newApplication( assemblers );
Application runtime = model.newInstance( polygene.spi() );
runtime.activate();
}
private static ApplicationDescriptor newApplication( final Assembler[][][] assemblers )
throws AssemblyException
{
return polygene.newApplicationModel( factory -> factory.newApplicationAssembly( assemblers ) );
}
// END SNIPPET: pancake
}
public static class full
{
static class CustomerViewComposite {}
static class CustomerEditComposite {}
static class CustomerListViewComposite {}
static class CustomerSearchComposite {}
static class CustomerEntity {}
static class CountryEntity {}
public static class AddressValue {}
public static class LdapAuthenticationAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) throws AssemblyException { }
}
public static class ThrinkAuthorizationAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) throws AssemblyException { }
}
public static class UserTrackingAuditAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) throws AssemblyException { }
}
public static class NeoAssembler implements Assembler
{
NeoAssembler( String path ) {}
public void assemble( ModuleAssembly module ) throws AssemblyException { }
}
// START SNIPPET: full
private static Energy4Java polygene;
private static Application application;
public static void main( String[] args )
throws Exception
{
// Create a Polygene Runtime
polygene = new Energy4Java();
// Create the application
application = polygene.newApplication( factory -> buildAssembly( factory.newApplicationAssembly() ) );
// Activate the application
application.activate();
}
static ApplicationAssembly buildAssembly( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly webLayer = createWebLayer( app );
LayerAssembly domainLayer = createDomainLayer( app );
LayerAssembly persistenceLayer = createInfrastructureLayer( app );
LayerAssembly authLayer = createAuth2Layer( app );
LayerAssembly messagingLayer = createMessagingLayer( app );
webLayer.uses( domainLayer );
domainLayer.uses( authLayer );
domainLayer.uses( persistenceLayer );
domainLayer.uses( messagingLayer );
return app;
}
static LayerAssembly createWebLayer( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly layer = app.layer( "web-layer" );
createCustomerWebModule( layer );
return layer;
}
static LayerAssembly createDomainLayer( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly layer = app.layer( "domain-layer" );
createCustomerDomainModule( layer );
// :
// :
return layer;
}
static LayerAssembly createInfrastructureLayer( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly layer = app.layer( "infrastructure-layer" );
createPersistenceModule( layer );
return layer;
}
static LayerAssembly createMessagingLayer( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly layer = app.layer( "messaging-layer" );
createWebServiceModule( layer );
createMessagingPersistenceModule( layer );
return layer;
}
static LayerAssembly createAuth2Layer( ApplicationAssembly application ) throws AssemblyException
{
LayerAssembly layer = application.layer( "auth2-layer" );
createAuthModule( layer );
return layer;
}
static void createCustomerWebModule( LayerAssembly layer ) throws AssemblyException
{
ModuleAssembly assembly = layer.module( "customer-web-module" );
assembly.transients( CustomerViewComposite.class, CustomerEditComposite.class,
CustomerListViewComposite.class, CustomerSearchComposite.class );
}
static void createCustomerDomainModule( LayerAssembly layer ) throws AssemblyException
{
ModuleAssembly assembly = layer.module( "customer-domain-module" );
assembly.entities( CustomerEntity.class, CountryEntity.class );
assembly.values( AddressValue.class );
}
static void createAuthModule( LayerAssembly layer ) throws AssemblyException
{
ModuleAssembly assembly = layer.module( "auth-module" );
new LdapAuthenticationAssembler().assemble( assembly );
new ThrinkAuthorizationAssembler().assemble( assembly );
new UserTrackingAuditAssembler().assemble( assembly );
}
static void createPersistenceModule( LayerAssembly layer ) throws AssemblyException
{
ModuleAssembly assembly = layer.module( "persistence-module" );
// Someone has created an assembler for the Neo EntityStore
new NeoAssembler( "./neostore" ).assemble( assembly );
}
// END SNIPPET: full
private static void createWebServiceModule( LayerAssembly layer ) throws AssemblyException
{
}
private static void createMessagingPersistenceModule( LayerAssembly layer ) throws AssemblyException
{
}
}
}
| core/bootstrap/src/test/java/org/apache/polygene/bootstrap/DocumentationSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package org.apache.polygene.bootstrap;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import org.apache.polygene.api.activation.ActivationException;
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.api.service.importer.InstanceImporter;
import org.apache.polygene.api.service.importer.NewObjectImporter;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.structure.ApplicationDescriptor;
import org.apache.polygene.api.structure.Module;
@SuppressWarnings( { "unused", "ConstantConditionalExpression", "MethodNameSameAsClassName" } )
public class DocumentationSupport
{
public static Predicate<ObjectAssembly> hasMyTypeSpecification =
item -> item.types().anyMatch( type -> type.equals( String.class ) );
public static class declarations
{
static class MyObject {}
interface MyTransient {}
interface MyValue {}
interface MyEntity {}
class MyService {}
void declaration()
{
Assembler objects =
// START SNIPPET: objects
( ModuleAssembly module ) -> module.objects( MyObject.class ).visibleIn( Visibility.layer )
// END SNIPPET: objects
;
Assembler transients =
// START SNIPPET: transients
( ModuleAssembly module ) -> module.transients( MyTransient.class ).visibleIn( Visibility.layer )
// END SNIPPET: transients
;
Assembler values =
// START SNIPPET: values
( ModuleAssembly module ) -> module.values( MyValue.class ).visibleIn( Visibility.layer )
// END SNIPPET: values
;
Assembler entities =
// START SNIPPET: entities
( ModuleAssembly module ) -> module.entities( MyEntity.class ).visibleIn( Visibility.layer )
// END SNIPPET: entities
;
Assembler services =
// START SNIPPET: services
( ModuleAssembly module ) -> module.services( MyService.class ).visibleIn( Visibility.layer )
// END SNIPPET: services
;
Assembler taggedServices =
// START SNIPPET: tagged-services
( ModuleAssembly module ) -> module.services( MyService.class ).taggedWith( "foo", "bar" )
// END SNIPPET: tagged-services
;
List<Assembler> importedServices = Arrays.asList(
// START SNIPPET: imported-services
( ModuleAssembly module ) -> module.importedServices( MyService.class )
.importedBy( InstanceImporter.class )
.setMetaInfo( new MyService() ),
// OR
( ModuleAssembly module ) -> {
module.objects( MyService.class );
module.importedServices( MyService.class ).importedBy( NewObjectImporter.class );
}
// END SNIPPET: imported-services
);
}
}
static class defaultPropertyValues
{
interface MyValue
{
Property<String> foo();
}
interface MyEntity
{
Property<String> cathedral();
}
void defaultPropertyValues()
{
Assembler assembler =
// START SNIPPET: properties-defaults
( ModuleAssembly module ) -> {
module.values( MyValue.class );
MyValue myValueDefaults = module.forMixin( MyValue.class ).declareDefaults();
myValueDefaults.foo().set( "bar" );
module.entities( MyEntity.class );
MyEntity myEntityDefaults = module.forMixin( MyEntity.class ).declareDefaults();
myEntityDefaults.cathedral().set( "bazar" );
}
// END SNIPPET: properties-defaults
;
}
}
public static class singleton
{
interface MyService {}
interface Stuff {}
void singleton()
throws ActivationException, AssemblyException
{
// START SNIPPET: singleton
SingletonAssembler assembler = new SingletonAssembler(
module -> {
module.services( MyService.class ).identifiedBy( "Foo" );
module.services( MyService.class ).identifiedBy( "Bar" );
module.objects( Stuff.class );
}
);
Module module = assembler.module();
Stuff stuff = module.newObject( Stuff.class );
// END SNIPPET: singleton
}
}
public static class pancake
{
public static class LoginAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class MenuAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class PerspectivesAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class ViewsAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class ReportingAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class PdfAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class BookkeepingAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class CashFlowAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class BalanceSheetAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class PricingAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
public static class ProductAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) { }
}
private static Energy4Java polygene;
// START SNIPPET: pancake
public static void main( String[] args )
throws Exception
{
polygene = new Energy4Java();
Assembler[][][] assemblers = new Assembler[][][] {
{ // View Layer
{ // Login Module
new LoginAssembler()
// :
},
{ // Main Workbench Module
new MenuAssembler(),
new PerspectivesAssembler(),
new ViewsAssembler()
// :
},
{ // Printing Module
new ReportingAssembler(),
new PdfAssembler()
// :
}
},
{ // Application Layer
{ // Accounting Module
new BookkeepingAssembler(),
new CashFlowAssembler(),
new BalanceSheetAssembler()
// :
},
{ // Inventory Module
new PricingAssembler(),
new ProductAssembler()
// :
}
},
{ // Domain Layer
// :
},
{ // Infrastructure Layer
// :
}
};
ApplicationDescriptor model = newApplication( assemblers );
Application runtime = model.newInstance( polygene.spi() );
runtime.activate();
}
private static ApplicationDescriptor newApplication( final Assembler[][][] assemblers )
throws AssemblyException
{
return polygene.newApplicationModel( factory -> factory.newApplicationAssembly( assemblers ) );
}
// END SNIPPET: pancake
}
public static class full
{
static class CustomerViewComposite {}
static class CustomerEditComposite {}
static class CustomerListViewComposite {}
static class CustomerSearchComposite {}
static class CustomerEntity {}
static class CountryEntity {}
static class AddressValue {}
public static class LdapAuthenticationAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) throws AssemblyException { }
}
public static class ThrinkAuthorizationAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) throws AssemblyException { }
}
public static class UserTrackingAuditAssembler implements Assembler
{
public void assemble( ModuleAssembly module ) throws AssemblyException { }
}
public static class NeoAssembler implements Assembler
{
NeoAssembler( String path ) {}
public void assemble( ModuleAssembly module ) throws AssemblyException { }
}
// START SNIPPET: full
private static Energy4Java polygene;
private static Application application;
public static void main( String[] args )
throws Exception
{
// Create a Polygene Runtime
polygene = new Energy4Java();
// Create the application
application = polygene.newApplication( factory -> buildAssembly( factory.newApplicationAssembly() ) );
// Activate the application
application.activate();
}
static ApplicationAssembly buildAssembly( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly webLayer = createWebLayer( app );
LayerAssembly domainLayer = createDomainLayer( app );
LayerAssembly persistenceLayer = createInfrastructureLayer( app );
LayerAssembly authLayer = createAuth2Layer( app );
LayerAssembly messagingLayer = createMessagingLayer( app );
webLayer.uses( domainLayer );
domainLayer.uses( authLayer );
domainLayer.uses( persistenceLayer );
domainLayer.uses( messagingLayer );
return app;
}
static LayerAssembly createWebLayer( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly layer = app.layer( "web-layer" );
createCustomerWebModule( layer );
return layer;
}
static LayerAssembly createDomainLayer( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly layer = app.layer( "domain-layer" );
createCustomerDomainModule( layer );
// :
// :
return layer;
}
static LayerAssembly createInfrastructureLayer( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly layer = app.layer( "infrastructure-layer" );
createPersistenceModule( layer );
return layer;
}
static LayerAssembly createMessagingLayer( ApplicationAssembly app ) throws AssemblyException
{
LayerAssembly layer = app.layer( "messaging-layer" );
createWebServiceModule( layer );
createMessagingPersistenceModule( layer );
return layer;
}
static LayerAssembly createAuth2Layer( ApplicationAssembly application ) throws AssemblyException
{
LayerAssembly layer = application.layer( "auth2-layer" );
createAuthModule( layer );
return layer;
}
static void createCustomerWebModule( LayerAssembly layer ) throws AssemblyException
{
ModuleAssembly assembly = layer.module( "customer-web-module" );
assembly.transients( CustomerViewComposite.class, CustomerEditComposite.class,
CustomerListViewComposite.class, CustomerSearchComposite.class );
}
static void createCustomerDomainModule( LayerAssembly layer ) throws AssemblyException
{
ModuleAssembly assembly = layer.module( "customer-domain-module" );
assembly.entities( CustomerEntity.class, CountryEntity.class );
assembly.values( AddressValue.class );
}
static void createAuthModule( LayerAssembly layer ) throws AssemblyException
{
ModuleAssembly assembly = layer.module( "auth-module" );
new LdapAuthenticationAssembler().assemble( assembly );
new ThrinkAuthorizationAssembler().assemble( assembly );
new UserTrackingAuditAssembler().assemble( assembly );
}
static void createPersistenceModule( LayerAssembly layer ) throws AssemblyException
{
ModuleAssembly assembly = layer.module( "persistence-module" );
// Someone has created an assembler for the Neo EntityStore
new NeoAssembler( "./neostore" ).assemble( assembly );
}
// END SNIPPET: full
private static void createWebServiceModule( LayerAssembly layer ) throws AssemblyException
{
}
private static void createMessagingPersistenceModule( LayerAssembly layer ) throws AssemblyException
{
}
}
}
| Minor fix to documentation support code
| core/bootstrap/src/test/java/org/apache/polygene/bootstrap/DocumentationSupport.java | Minor fix to documentation support code | <ide><path>ore/bootstrap/src/test/java/org/apache/polygene/bootstrap/DocumentationSupport.java
<ide>
<ide> static class CountryEntity {}
<ide>
<del> static class AddressValue {}
<add> public static class AddressValue {}
<ide>
<ide> public static class LdapAuthenticationAssembler implements Assembler
<ide> { |
|
Java | apache-2.0 | 8c1ca0b7d68f6d0fe1a906023295b3dfefbeae27 | 0 | ebean-orm/ebean-dbmigration | package io.ebean.migration;
import io.ebean.docker.commands.DbConfig;
import io.ebean.docker.commands.MySqlConfig;
import io.ebean.docker.commands.MySqlContainer;
import io.ebean.docker.commands.NuoDBConfig;
import io.ebean.docker.commands.NuoDBContainer;
import io.ebean.docker.commands.OracleConfig;
import io.ebean.docker.commands.OracleContainer;
import io.ebean.docker.commands.PostgresConfig;
import io.ebean.docker.commands.PostgresContainer;
import io.ebean.docker.commands.SqlServerConfig;
import io.ebean.docker.commands.SqlServerContainer;
import org.testng.annotations.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MigrationRunner_platform_Test {
private final NuoDBContainer nuoDBContainer = createNuoDB();
private final PostgresContainer postgresContainer = createPostgres();
private final SqlServerContainer sqlServerContainer = createSqlServer();
private final MySqlContainer mysqlContainer = createMySqlContainer();
private final OracleContainer oracleContainer = createOracleContainer();
private static void setContainerName(DbConfig config, String suffix) {
config.setContainerName("test_ebean_migration_" + suffix);
config.setUser("mig_test");
config.setDbName("mig_test");
}
private static NuoDBContainer createNuoDB() {
NuoDBConfig config = new NuoDBConfig();
config.setSchema("mig_test");
config.setUser("mig_test");
config.setPassword("test");
return new NuoDBContainer(config);
}
private static PostgresContainer createPostgres() {
PostgresConfig config = new PostgresConfig("10.1");
config.setPort("9823");
setContainerName(config, "pg10");
return new PostgresContainer(config);
}
private static SqlServerContainer createSqlServer() {
SqlServerConfig config = new SqlServerConfig("2017-GA-ubuntu");
config.setPort("2433");
setContainerName(config, "sql17");
return new SqlServerContainer(config);
}
private static MySqlContainer createMySqlContainer() {
MySqlConfig config = new MySqlConfig("8.0");
setContainerName(config, "mysql");
return new MySqlContainer(config);
}
private static OracleContainer createOracleContainer() {
OracleConfig config = new OracleConfig("latest");
setContainerName(config, "oracle");
config.setDbName("XE");
config.setImage("oracleinanutshell/oracle-xe-11g:latest");
return new OracleContainer(config);
}
private MigrationConfig newMigrationConfig() {
MigrationConfig config = new MigrationConfig();
config.setDbUsername("mig_test");
config.setDbPassword("test");
return config;
}
private MigrationConfig postgresMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbDriver("org.postgresql.Driver");
config.setDbUrl(postgresContainer.jdbcUrl());
return config;
}
private MigrationConfig sqlServerMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbPassword("SqlS3rv#r");
config.setDbDriver("com.microsoft.sqlserver.jdbc.SQLServerDriver");
config.setDbUrl(sqlServerContainer.jdbcUrl());
return config;
}
private MigrationConfig nuodDbMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbDriver("com.nuodb.jdbc.Driver");
config.setDbUrl(nuoDBContainer.jdbcUrl());
config.setDbSchema("mig_test");
config.setDbUsername("mig_test");
config.setDbPassword("test");
return config;
}
private MigrationConfig mysqlMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbDriver("com.mysql.cj.jdbc.Driver");
config.setDbUrl(mysqlContainer.jdbcUrl());
return config;
}
private MigrationConfig oracleMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbDriver("oracle.jdbc.OracleDriver");
config.setDbUrl(oracleContainer.jdbcUrl());
return config;
}
@Test
public void postgres_migration() throws SQLException {
postgresContainer.start();
MigrationConfig config = postgresMigrationConfig();
config.setMigrationPath("dbmig");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
System.out.println("-- run 2 --");
runner.run();
System.out.println("-- run 3 --");
config.setMigrationPath("dbmig2");
runner.run();
try (Connection connection = postgresContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from m2");
readQuery(connection, "select * from m3");
}
postgresContainer.stopRemove();
}
@Test(enabled = false)
public void sqlServer_migration() throws SQLException {
sqlServerContainer.startWithDropCreate();
MigrationConfig config = sqlServerMigrationConfig();
config.setMigrationPath("dbmig_sqlserver");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
try (Connection connection = sqlServerContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from m2");
readQuery(connection, "select * from m3");
}
// sqlServerContainer.stopRemove();
}
@Test
public void mysql_migration() throws SQLException {
mysqlContainer.startWithDropCreate();
MigrationConfig config = mysqlMigrationConfig();
config.setMigrationPath("dbmig_basic");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
try (Connection connection = mysqlContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from m2");
readQuery(connection, "select * from m3");
}
mysqlContainer.stopRemove();
}
@Test(enabled = false)
public void nuodb_migration() throws SQLException {
//nuoDBContainer.stopRemove();
nuoDBContainer.startWithDropCreate();
MigrationConfig config = nuodDbMigrationConfig();
config.setMigrationPath("dbmig_nuodb");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
try (Connection connection = nuoDBContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from orp_master");
readQuery(connection, "select * from orp_master_with_history");
}
nuoDBContainer.stop();
}
@Test(enabled = false)
public void oracle_migration() throws SQLException {
oracleContainer.startWithDropCreate();
MigrationConfig config = oracleMigrationConfig();
config.setMigrationPath("dbmig_basic");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
try (Connection connection = oracleContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from m2");
readQuery(connection, "select * from m3");
}
//oracleContainer.stopRemove();
}
private void readQuery(Connection connection, String sql) throws SQLException {
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
try (ResultSet rset = stmt.executeQuery()) {
while (rset.next()) {
rset.getObject(1);
}
}
}
}
}
| src/test/java/io/ebean/migration/MigrationRunner_platform_Test.java | package io.ebean.migration;
import io.ebean.docker.commands.DbConfig;
import io.ebean.docker.commands.MySqlConfig;
import io.ebean.docker.commands.MySqlContainer;
import io.ebean.docker.commands.NuoDBConfig;
import io.ebean.docker.commands.NuoDBContainer;
import io.ebean.docker.commands.OracleConfig;
import io.ebean.docker.commands.OracleContainer;
import io.ebean.docker.commands.PostgresConfig;
import io.ebean.docker.commands.PostgresContainer;
import io.ebean.docker.commands.SqlServerConfig;
import io.ebean.docker.commands.SqlServerContainer;
import org.testng.annotations.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MigrationRunner_platform_Test {
private final NuoDBContainer nuoDBContainer = createNuoDB();
private final PostgresContainer postgresContainer = createPostgres();
private final SqlServerContainer sqlServerContainer = createSqlServer();
private final MySqlContainer mysqlContainer = createMySqlContainer();
private final OracleContainer oracleContainer = createOracleContainer();
private static void setContainerName(DbConfig config, String suffix) {
config.setContainerName("test_ebean_migration_" + suffix);
config.setUser("mig_test");
config.setDbName("mig_test");
}
private static NuoDBContainer createNuoDB() {
NuoDBConfig config = new NuoDBConfig();
config.setSchema("mig_test");
config.setUser("mig_test");
config.setPassword("test");
return new NuoDBContainer(config);
}
private static PostgresContainer createPostgres() {
PostgresConfig config = new PostgresConfig("10.1");
config.setPort("9823");
setContainerName(config, "pg10");
return new PostgresContainer(config);
}
private static SqlServerContainer createSqlServer() {
SqlServerConfig config = new SqlServerConfig("2017-GA-ubuntu");
config.setPort("2433");
setContainerName(config, "sql17");
return new SqlServerContainer(config);
}
private static MySqlContainer createMySqlContainer() {
MySqlConfig config = new MySqlConfig("8.0");
setContainerName(config, "mysql");
return new MySqlContainer(config);
}
private static OracleContainer createOracleContainer() {
OracleConfig config = new OracleConfig("latest");
setContainerName(config, "oracle");
config.setDbName("XE");
config.setImage("oracleinanutshell/oracle-xe-11g:latest");
return new OracleContainer(config);
}
private MigrationConfig newMigrationConfig() {
MigrationConfig config = new MigrationConfig();
config.setDbUsername("mig_test");
config.setDbPassword("test");
return config;
}
private MigrationConfig postgresMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbDriver("org.postgresql.Driver");
config.setDbUrl(postgresContainer.jdbcUrl());
return config;
}
private MigrationConfig sqlServerMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbPassword("SqlS3rv#r");
config.setDbDriver("com.microsoft.sqlserver.jdbc.SQLServerDriver");
config.setDbUrl(sqlServerContainer.jdbcUrl());
return config;
}
private MigrationConfig nuodDbMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbDriver("com.nuodb.jdbc.Driver");
config.setDbUrl(nuoDBContainer.jdbcUrl());
config.setDbSchema("mig_test");
config.setDbUsername("mig_test");
config.setDbPassword("test");
return config;
}
private MigrationConfig mysqlMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbDriver("com.mysql.cj.jdbc.Driver");
config.setDbUrl(mysqlContainer.jdbcUrl());
return config;
}
private MigrationConfig oracleMigrationConfig() {
MigrationConfig config = newMigrationConfig();
config.setDbDriver("oracle.jdbc.OracleDriver");
config.setDbUrl(oracleContainer.jdbcUrl());
return config;
}
@Test
public void postgres_migration() throws SQLException {
postgresContainer.start();
MigrationConfig config = postgresMigrationConfig();
config.setMigrationPath("dbmig");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
System.out.println("-- run 2 --");
runner.run();
System.out.println("-- run 3 --");
config.setMigrationPath("dbmig2");
runner.run();
try (Connection connection = postgresContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from m2");
readQuery(connection, "select * from m3");
}
postgresContainer.stopRemove();
}
@Test
public void sqlServer_migration() throws SQLException {
sqlServerContainer.startWithDropCreate();
MigrationConfig config = sqlServerMigrationConfig();
config.setMigrationPath("dbmig_sqlserver");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
try (Connection connection = sqlServerContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from m2");
readQuery(connection, "select * from m3");
}
// sqlServerContainer.stopRemove();
}
@Test
public void mysql_migration() throws SQLException {
mysqlContainer.startWithDropCreate();
MigrationConfig config = mysqlMigrationConfig();
config.setMigrationPath("dbmig_basic");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
try (Connection connection = mysqlContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from m2");
readQuery(connection, "select * from m3");
}
mysqlContainer.stopRemove();
}
@Test
public void nuodb_migration() throws SQLException {
//nuoDBContainer.stopRemove();
nuoDBContainer.startWithDropCreate();
MigrationConfig config = nuodDbMigrationConfig();
config.setMigrationPath("dbmig_nuodb");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
try (Connection connection = nuoDBContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from orp_master");
readQuery(connection, "select * from orp_master_with_history");
}
nuoDBContainer.stop();
}
@Test(enabled = false)
public void oracle_migration() throws SQLException {
oracleContainer.startWithDropCreate();
MigrationConfig config = oracleMigrationConfig();
config.setMigrationPath("dbmig_basic");
MigrationRunner runner = new MigrationRunner(config);
runner.run();
try (Connection connection = oracleContainer.createConnection()) {
readQuery(connection, "select * from m1");
readQuery(connection, "select * from m2");
readQuery(connection, "select * from m3");
}
//oracleContainer.stopRemove();
}
private void readQuery(Connection connection, String sql) throws SQLException {
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
try (ResultSet rset = stmt.executeQuery()) {
while (rset.next()) {
rset.getObject(1);
}
}
}
}
}
| Disable NuoDB and SqlServer component tests by default
| src/test/java/io/ebean/migration/MigrationRunner_platform_Test.java | Disable NuoDB and SqlServer component tests by default | <ide><path>rc/test/java/io/ebean/migration/MigrationRunner_platform_Test.java
<ide> postgresContainer.stopRemove();
<ide> }
<ide>
<del> @Test
<add> @Test(enabled = false)
<ide> public void sqlServer_migration() throws SQLException {
<ide>
<ide> sqlServerContainer.startWithDropCreate();
<ide> mysqlContainer.stopRemove();
<ide> }
<ide>
<del> @Test
<add> @Test(enabled = false)
<ide> public void nuodb_migration() throws SQLException {
<ide>
<ide> //nuoDBContainer.stopRemove(); |
|
Java | bsd-3-clause | e661a551cb153951daabae12b7cebf6232cfd9b7 | 0 | myntra/react-native,hoangpham95/react-native,pandiaraj44/react-native,myntra/react-native,facebook/react-native,myntra/react-native,facebook/react-native,hoangpham95/react-native,facebook/react-native,janicduplessis/react-native,hoangpham95/react-native,hoangpham95/react-native,janicduplessis/react-native,myntra/react-native,arthuralee/react-native,janicduplessis/react-native,javache/react-native,javache/react-native,myntra/react-native,javache/react-native,javache/react-native,facebook/react-native,myntra/react-native,javache/react-native,facebook/react-native,javache/react-native,javache/react-native,pandiaraj44/react-native,myntra/react-native,janicduplessis/react-native,hoangpham95/react-native,arthuralee/react-native,pandiaraj44/react-native,facebook/react-native,janicduplessis/react-native,janicduplessis/react-native,hoangpham95/react-native,pandiaraj44/react-native,javache/react-native,pandiaraj44/react-native,hoangpham95/react-native,facebook/react-native,facebook/react-native,arthuralee/react-native,arthuralee/react-native,hoangpham95/react-native,javache/react-native,pandiaraj44/react-native,pandiaraj44/react-native,janicduplessis/react-native,myntra/react-native,pandiaraj44/react-native,janicduplessis/react-native,facebook/react-native,myntra/react-native,arthuralee/react-native | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.animated;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.JavaOnlyMap;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.UIManager;
import java.util.HashMap;
import java.util.Map;
/**
* Animated node that represents view properties. There is a special handling logic implemented for
* the nodes of this type in {@link NativeAnimatedNodesManager} that is responsible for extracting a
* map of updated properties, which can be then passed down to the view.
*/
/*package*/ class PropsAnimatedNode extends AnimatedNode {
private int mConnectedViewTag = -1;
private final NativeAnimatedNodesManager mNativeAnimatedNodesManager;
private final Map<String, Integer> mPropNodeMapping;
private final JavaOnlyMap mPropMap;
@Nullable private UIManager mUIManager;
PropsAnimatedNode(ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) {
ReadableMap props = config.getMap("props");
ReadableMapKeySetIterator iter = props.keySetIterator();
mPropNodeMapping = new HashMap<>();
while (iter.hasNextKey()) {
String propKey = iter.nextKey();
int nodeIndex = props.getInt(propKey);
mPropNodeMapping.put(propKey, nodeIndex);
}
mPropMap = new JavaOnlyMap();
mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
}
public void connectToView(int viewTag, UIManager uiManager) {
if (mConnectedViewTag != -1) {
throw new JSApplicationIllegalArgumentException(
"Animated node " + mTag + " is " + "already attached to a view: " + mConnectedViewTag);
}
mConnectedViewTag = viewTag;
mUIManager = uiManager;
}
public void disconnectFromView(int viewTag) {
if (mConnectedViewTag != viewTag && mConnectedViewTag != -1) {
throw new JSApplicationIllegalArgumentException(
"Attempting to disconnect view that has "
+ "not been connected with the given animated node: "
+ viewTag
+ " but is connected to view "
+ mConnectedViewTag);
}
mConnectedViewTag = -1;
}
public void restoreDefaultValues() {
// Cannot restore default values if this view has already been disconnected.
if (mConnectedViewTag == -1) {
return;
}
ReadableMapKeySetIterator it = mPropMap.keySetIterator();
while (it.hasNextKey()) {
mPropMap.putNull(it.nextKey());
}
mUIManager.synchronouslyUpdateViewOnUIThread(mConnectedViewTag, mPropMap);
}
public final void updateView() {
if (mConnectedViewTag == -1) {
return;
}
for (Map.Entry<String, Integer> entry : mPropNodeMapping.entrySet()) {
@Nullable AnimatedNode node = mNativeAnimatedNodesManager.getNodeById(entry.getValue());
if (node == null) {
throw new IllegalArgumentException("Mapped property node does not exists");
} else if (node instanceof StyleAnimatedNode) {
((StyleAnimatedNode) node).collectViewUpdates(mPropMap);
} else if (node instanceof ValueAnimatedNode) {
Object animatedObject = ((ValueAnimatedNode) node).getAnimatedObject();
if (animatedObject instanceof String) {
mPropMap.putString(entry.getKey(), (String) animatedObject);
} else {
mPropMap.putDouble(entry.getKey(), ((ValueAnimatedNode) node).getValue());
}
} else {
throw new IllegalArgumentException(
"Unsupported type of node used in property node " + node.getClass());
}
}
mUIManager.synchronouslyUpdateViewOnUIThread(mConnectedViewTag, mPropMap);
}
}
| ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.animated;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.JavaOnlyMap;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.UIManager;
import java.util.HashMap;
import java.util.Map;
/**
* Animated node that represents view properties. There is a special handling logic implemented for
* the nodes of this type in {@link NativeAnimatedNodesManager} that is responsible for extracting a
* map of updated properties, which can be then passed down to the view.
*/
/*package*/ class PropsAnimatedNode extends AnimatedNode {
private int mConnectedViewTag = -1;
private final NativeAnimatedNodesManager mNativeAnimatedNodesManager;
private final Map<String, Integer> mPropNodeMapping;
private final JavaOnlyMap mPropMap;
@Nullable private UIManager mUIManager;
PropsAnimatedNode(ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) {
ReadableMap props = config.getMap("props");
ReadableMapKeySetIterator iter = props.keySetIterator();
mPropNodeMapping = new HashMap<>();
while (iter.hasNextKey()) {
String propKey = iter.nextKey();
int nodeIndex = props.getInt(propKey);
mPropNodeMapping.put(propKey, nodeIndex);
}
mPropMap = new JavaOnlyMap();
mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
}
public void connectToView(int viewTag, UIManager uiManager) {
if (mConnectedViewTag != -1) {
throw new JSApplicationIllegalArgumentException(
"Animated node " + mTag + " is " + "already attached to a view");
}
mConnectedViewTag = viewTag;
mUIManager = uiManager;
}
public void disconnectFromView(int viewTag) {
if (mConnectedViewTag != viewTag) {
throw new JSApplicationIllegalArgumentException(
"Attempting to disconnect view that has "
+ "not been connected with the given animated node");
}
mConnectedViewTag = -1;
}
public void restoreDefaultValues() {
// Cannot restore default values if this view has already been disconnected.
if (mConnectedViewTag == -1) {
return;
}
ReadableMapKeySetIterator it = mPropMap.keySetIterator();
while (it.hasNextKey()) {
mPropMap.putNull(it.nextKey());
}
mUIManager.synchronouslyUpdateViewOnUIThread(mConnectedViewTag, mPropMap);
}
public final void updateView() {
if (mConnectedViewTag == -1) {
return;
}
for (Map.Entry<String, Integer> entry : mPropNodeMapping.entrySet()) {
@Nullable AnimatedNode node = mNativeAnimatedNodesManager.getNodeById(entry.getValue());
if (node == null) {
throw new IllegalArgumentException("Mapped property node does not exists");
} else if (node instanceof StyleAnimatedNode) {
((StyleAnimatedNode) node).collectViewUpdates(mPropMap);
} else if (node instanceof ValueAnimatedNode) {
Object animatedObject = ((ValueAnimatedNode) node).getAnimatedObject();
if (animatedObject instanceof String) {
mPropMap.putString(entry.getKey(), (String) animatedObject);
} else {
mPropMap.putDouble(entry.getKey(), ((ValueAnimatedNode) node).getValue());
}
} else {
throw new IllegalArgumentException(
"Unsupported type of node used in property node " + node.getClass());
}
}
mUIManager.synchronouslyUpdateViewOnUIThread(mConnectedViewTag, mPropMap);
}
}
| Potential fix for, and more diagnostics for, NativeAnimatedModule crash
Summary:
Searching for details and maybe a fix for T68843308 crashing in disconnectFromView, "Attempting to disconnect view that has not been connected with the given animated node".
May be related to recent refactoring but it's not clear. Change logic slightly and add more diagnostic information.
Changelog: [Internal]
Reviewed By: shergin
Differential Revision: D22153179
fbshipit-source-id: b95dbaf01ae8bca154c61442898b0f9d3aebb4de
| ReactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java | Potential fix for, and more diagnostics for, NativeAnimatedModule crash | <ide><path>eactAndroid/src/main/java/com/facebook/react/animated/PropsAnimatedNode.java
<ide> public void connectToView(int viewTag, UIManager uiManager) {
<ide> if (mConnectedViewTag != -1) {
<ide> throw new JSApplicationIllegalArgumentException(
<del> "Animated node " + mTag + " is " + "already attached to a view");
<add> "Animated node " + mTag + " is " + "already attached to a view: " + mConnectedViewTag);
<ide> }
<ide> mConnectedViewTag = viewTag;
<ide> mUIManager = uiManager;
<ide> }
<ide>
<ide> public void disconnectFromView(int viewTag) {
<del> if (mConnectedViewTag != viewTag) {
<add> if (mConnectedViewTag != viewTag && mConnectedViewTag != -1) {
<ide> throw new JSApplicationIllegalArgumentException(
<ide> "Attempting to disconnect view that has "
<del> + "not been connected with the given animated node");
<add> + "not been connected with the given animated node: "
<add> + viewTag
<add> + " but is connected to view "
<add> + mConnectedViewTag);
<ide> }
<ide>
<ide> mConnectedViewTag = -1; |
|
Java | mit | e5a2100aaaf868e5059252dfacf90f85dd09e437 | 0 | dandudzi/SoundMeterPG | package pl.gda.pg.eti.kask.soundmeterpg;
/**
* Created by Daniel on 21.06.2016.
*/
public class GierlowskiZawszePodkresla {
//TODO zrob to filip
}
| app/src/main/java/pl/gda/pg/eti/kask/soundmeterpg/GierlowskiZawszePodkresla.java | package pl.gda.pg.eti.kask.soundmeterpg;
/**
* Created by Daniel on 21.06.2016.
*/
public class GierlowskiZawszePodkresla {
}
| Testowa zmiana
| app/src/main/java/pl/gda/pg/eti/kask/soundmeterpg/GierlowskiZawszePodkresla.java | Testowa zmiana | <ide><path>pp/src/main/java/pl/gda/pg/eti/kask/soundmeterpg/GierlowskiZawszePodkresla.java
<ide> * Created by Daniel on 21.06.2016.
<ide> */
<ide> public class GierlowskiZawszePodkresla {
<add> //TODO zrob to filip
<ide> } |
|
Java | apache-2.0 | c22388e4e527c7b36b56004cbb98f064560fd633 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | package edu.columbia.gemma.web;
/**
* Constant values used throughout the application.
* <p>Originally from Appfuse, to support code imported from Appfuse.
* <hr>
* <p>
* Copyright (c) 2004-2005 Columbia University
*
* @author <a href="mailto:[email protected]">Matt Raible</a>
* @author pavlidis
* @version $Id$
*/
public class Constants {
// ~ Static fields/initializers =============================================
/**
* The application scoped attribute for persistence engine and class that implements it
*/
public static final String DAO_TYPE = "daoType";
public static final String DAO_TYPE_HIBERNATE = "hibernate";
/** Application scoped attribute for authentication url */
public static final String AUTH_URL = "authURL";
/** Application scoped attributes for SSL Switching */
public static final String HTTP_PORT = "httpPort";
public static final String HTTPS_PORT = "httpsPort";
/** The application scoped attribute for indicating a secure login */
public static final String SECURE_LOGIN = "secureLogin";
/** The encryption algorithm key to be used for passwords */
public static final String ENC_ALGORITHM = "algorithm";
/** A flag to indicate if passwords should be encrypted */
public static final String ENCRYPT_PASSWORD = "encryptPassword";
/** File separator from System properties */
public static final String FILE_SEP = System.getProperty( "file.separator" );
/** User home from System properties */
public static final String USER_HOME = System.getProperty( "user.home" ) + FILE_SEP;
/**
* The session scope attribute under which the breadcrumb ArrayStack is stored
*/
public static final String BREADCRUMB = "breadcrumbs";
/**
* The session scope attribute under which the User object for the currently logged in user is stored.
*/
public static final String USER_KEY = "currentUserForm";
/**
* The request scope attribute under which an editable user form is stored
*/
public static final String USER_EDIT_KEY = "userForm";
/**
* The request scope attribute that holds the user list
*/
public static final String USER_LIST = "userList";
/**
* The request scope attribute for indicating a newly-registered user
*/
public static final String REGISTERED = "registered";
/**
* The name of the Administrator role, as specified in web.xml
*/
public static final String ADMIN_ROLE = "admin";
/**
* The name of the User role, as specified in web.xml
*/
public static final String USER_ROLE = "user";
/**
* The name of the user's role list, a request-scoped attribute when adding/editing a user.
*/
public static final String USER_ROLES = "userRoles";
/**
* The name of the available roles list, a request-scoped attribute when adding/editing a user.
*/
public static final String AVAILABLE_ROLES = "availableRoles";
/**
* Name of cookie for "Remember Me" functionality.
*/
public static final String LOGIN_COOKIE = "sessionId";
/**
* The name of the configuration hashmap stored in application scope.
*/
public static final String CONFIG = "appConfig";
}
| src/web/edu/columbia/gemma/web/Constants.java | package edu.columbia.gemma.web;
/**
* Constant values used throughout the application.
* <p>Originally from Appfuse, to support code imported from Appfuse.
* <hr>
* <p>
* Copyright (c) 2004-2005 Columbia University
*
* @author <a href="mailto:[email protected]">Matt Raible</a>
* @author pavlidis
* @version $Id$
*/
public class Constants {
// ~ Static fields/initializers =============================================
/**
* The application scoped attribute for persistence engine and class that implements it
*/
public static final String DAO_TYPE = "daoType";
public static final String DAO_TYPE_HIBERNATE = "hibernate";
/** Application scoped attribute for authentication url */
public static final String AUTH_URL = "authURL";
/** Application scoped attributes for SSL Switching */
public static final String HTTP_PORT = "httpPort";
public static final String HTTPS_PORT = "httpsPort";
/** The application scoped attribute for indicating a secure login */
public static final String SECURE_LOGIN = "secureLogin";
/** The encryption algorithm key to be used for passwords */
public static final String ENC_ALGORITHM = "algorithm";
/** A flag to indicate if passwords should be encrypted */
public static final String ENCRYPT_PASSWORD = "encryptPassword";
/** File separator from System properties */
public static final String FILE_SEP = System.getProperty( "file.separator" );
/** User home from System properties */
public static final String USER_HOME = System.getProperty( "user.home" ) + FILE_SEP;
/**
* The session scope attribute under which the breadcrumb ArrayStack is stored
*/
public static final String BREADCRUMB = "breadcrumbs";
/**
* The session scope attribute under which the User object for the currently logged in user is stored.
*/
public static final String USER_KEY = "currentUserForm";
/**
* The request scope attribute under which an editable user form is stored
*/
public static final String USER_EDIT_KEY = "userForm";
/**
* The request scope attribute that holds the user list
*/
public static final String USER_LIST = "userList";
/**
* The request scope attribute for indicating a newly-registered user
*/
public static final String REGISTERED = "registered";
/**
* The name of the Administrator role, as specified in web.xml
*/
public static final String ADMIN_ROLE = "admin";
/**
* The name of the User role, as specified in web.xml
*/
public static final String USER_ROLE = "tomcat";
/**
* The name of the user's role list, a request-scoped attribute when adding/editing a user.
*/
public static final String USER_ROLES = "userRoles";
/**
* The name of the available roles list, a request-scoped attribute when adding/editing a user.
*/
public static final String AVAILABLE_ROLES = "availableRoles";
/**
* Name of cookie for "Remember Me" functionality.
*/
public static final String LOGIN_COOKIE = "sessionId";
/**
* The name of the configuration hashmap stored in application scope.
*/
public static final String CONFIG = "appConfig";
}
| change name of user role from tomcat to 'user'.
| src/web/edu/columbia/gemma/web/Constants.java | change name of user role from tomcat to 'user'. | <ide><path>rc/web/edu/columbia/gemma/web/Constants.java
<ide> /**
<ide> * The name of the User role, as specified in web.xml
<ide> */
<del> public static final String USER_ROLE = "tomcat";
<add> public static final String USER_ROLE = "user";
<ide>
<ide> /**
<ide> * The name of the user's role list, a request-scoped attribute when adding/editing a user. |
|
JavaScript | mit | 27ca1d30e7110bdac6b174292ec59781503e7378 | 0 | LivelyKernel/lively.morphic,LivelyKernel/lively.morphic | import { obj, arr, string, properties } from "lively.lang";
import { Rectangle, Color } from "lively.graphics";
import { Morph } from "../index.js";
import { defaultStyle, defaultAttributes } from "../rendering/morphic-default.js";
import { h } from "virtual-dom";
import { Icon, Icons } from "../components/icons.js";
import { signal } from "lively.bindings";
import { splitTextAndAttributesIntoLines } from "./attributes.js";
import { RichTextControl } from "./ui.js";
export class Label extends Morph {
static get properties() {
return {
fill: {defaultValue: Color.transparent},
draggable: {defaultValue: false},
nativeCursor: {defaultValue: "default"},
isIcon: {
derived: true,
get() {
return properties.values(Icons).map(({code}) => code).includes(this.textString)
}
},
value: {
derived: true, after: ["textAndAttributes", "textString"],
get() {
var {textAndAttributes} = this;
if (textAndAttributes.length <= 2) {
var [text, style] = textAndAttributes;
if (!Object.keys(style || {}).length) return text || "";
}
return textAndAttributes;
},
set(value) {
typeof value === "string" ?
this.textString = value :
this.textAndAttributes = value;
}
},
textString: {
derived: true, after: ["textAndAttributes"],
get() { return this.textAndAttributes.map((text, i) => i % 2==0 ? text : "").join(""); },
set(value) { this.textAndAttributes = [value, null]; }
},
textAndAttributes: {
get() {
var val = this.getProperty("textAndAttributes");
if (!val || val.length < 1) val = ["", null];
return val;
},
set(value) {
if (!Array.isArray(value)) value = [String(value), {}];
if (value.length === 0) value = ["", {}];
this._cachedTextBounds = null;
this.setProperty("textAndAttributes", value);
if (this.autofit) this._needsFit = true;
signal(this, "value", value);
}
},
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// valueAndAnnotation is a way to put rich text content followed by a right
// aligned annotation into a label. It simply is using textAndAttributes with
// the convention that the last string/attribue pair in textAndAttributes is the
// annotation (the attribute includes the textStyleClass "annotation")
valueAndAnnotation: {
derived: true, after: ["textAndAttributes"],
get() {
var value = this.textAndAttributes, annotation = null;
if (value.length > 2) {
var [string, props] = value.slice(-2);
if (props && props.textStyleClasses && props.textStyleClasses.includes("annotation")) {
value = value.slice(0, -2);
annotation = [string, props];
}
}
return {value, annotation};
},
set(valueAndAnnotation) {
var {value, annotation} = valueAndAnnotation;
// Ensure value is in the right format for being the prefix in textAndAttributes
if (!value) value = "";
if (typeof value === "string") value = [value, null]
if (!Array.isArray(value)) value = [String(value), null];
var textAndAttributes = value.slice();
// convert and add the annotation
if (annotation) {
if (typeof annotation === "string") annotation = [annotation, null];
var annAttr = annotation[1];
if (!annAttr) annAttr = annotation[1] = {};
textAndAttributes.push(...annotation);
annAttr.textStyleClasses = (annAttr.textStyleClasses || []).concat("annotation");
if (!annAttr.textStyleClasses.includes("annotation"))
annAttr.textStyleClasses.push("annotation");
}
this.textAndAttributes = textAndAttributes;
}
},
autofit: {
defaultValue: true,
set(value) {
this.setProperty("autofit", value);
if (value) this._needsFit = true;
}
},
padding: {
type: "Rectangle",
isStyleProp: true,
defaultValue: Rectangle.inset(0),
initialize(value) { this.padding = value; /*for num -> rect conversion*/},
set(value) {
if (!value) value = Rectangle.inset(0);
this._cachedTextBounds = null;
this.setProperty("padding", typeof value === "number" ? Rectangle.inset(value) : value);
if (this.autofit) this._needsFit = true;
}
},
fontFamily: {
isStyleProp: true,
type: "Enum",
values: RichTextControl.basicFontItems().map(f => f.value),
defaultValue: "Sans-Serif",
set(fontFamily) {
this._cachedTextBounds = null;
this.setProperty("fontFamily", fontFamily);
if (this.autofit) this._needsFit = true;
}
},
fontSize: {
type: "Number",
min: 1,
isStyleProp: true,
defaultValue: 12,
set(fontSize) {
this._cachedTextBounds = null;
this.setProperty("fontSize", fontSize);
if (this.autofit) this._needsFit = true;
}
},
fontColor: {type: "Color", isStyleProp: true, defaultValue: Color.black},
fontWeight: {
type: "Enum",
values: ["bold", "bolder", "light", "lighter"],
isStyleProp: true,
defaultValue: "normal",
set(fontWeight) {
this._cachedTextBounds = null;
this.setProperty("fontWeight", fontWeight);
if (this.autofit) this._needsFit = true;
}
},
fontStyle: {
type: "Enum",
values: ["normal", "italic", "oblique"],
isStyleProp: true,
defaultValue: "normal",
set(fontStyle) {
this._cachedTextBounds = null;
this.setProperty("fontStyle", fontStyle);
if (this.autofit) this._needsFit = true;
}
},
textDecoration: {defaultValue: "none"},
textStyleClasses: {
defaultValue: undefined,
set(textStyleClasses) {
this._cachedTextBounds = null;
this.setProperty("textStyleClasses", textStyleClasses);
if (this.autofit) this._needsFit = true;
}
}
}
}
static icon(iconName, props = {prefix: "", suffix: ""}) {
return Icon.makeLabel(iconName, props);
}
constructor(props = {}) {
var { fontMetric, position, rightCenter, leftCenter, topCenter,
bottom, top, right, left, bottomCenter, bottomLeft, bottomRight,
topRight, topLeft, center, extent } = props;
super(obj.dissoc(props, ["fontMetric"]));
if (fontMetric)
this._fontMetric = fontMetric;
this._cachedTextBounds = null;
this.fit();
// Update position + extent after fit
if (extent !== undefined) this.extent = extent;
if (position !== undefined) this.position = position;
if (rightCenter !== undefined) this.rightCenter = rightCenter;
if (leftCenter !== undefined) this.leftCenter = leftCenter;
if (topCenter !== undefined) this.topCenter = topCenter;
if (bottom !== undefined) this.bottom = bottom;
if (top !== undefined) this.top = top;
if (right !== undefined) this.right = right;
if (left !== undefined) this.left = left;
if (bottomCenter !== undefined) this.bottomCenter = bottomCenter;
if (bottomLeft !== undefined) this.bottomLeft = bottomLeft;
if (bottomRight !== undefined) this.bottomRight = bottomRight;
if (topRight !== undefined) this.topRight = topRight;
if (topLeft !== undefined) this.topLeft = topLeft;
if (center !== undefined) this.center = center;
}
get isLabel() { return true }
get textStyle() {
return obj.select(this, [
"textStyleClasses",
"textDecoration",
"fontStyle",
"fontWeight",
"fontColor",
"fontSize",
"fontFamily"
]);
}
fit() {
this.extent = this.textBounds().extent();
this._needsFit = false;
return this;
}
fitIfNeeded() {
if (this._needsFit) { this.fit(); }
}
get textAndAttributesOfLines() {
return splitTextAndAttributesIntoLines(this.textAndAttributes, "\n");
}
textBoundsSingleChunk() {
// text bounds not considering "chunks", i.e. only default text style is
// used
var fm = this._fontMetric || this.env.fontMetric,
[text, chunkStyle] = this.textAndAttributes,
style = {...this.textStyle, ...chunkStyle},
padding = this.padding,
width, height;
if (!fm.isProportional(style.fontFamily)) {
var {width: charWidth, height: charHeight} = fm.sizeFor(style, "x");
width = text.length * charWidth;
height = charHeight;
} else {
({width, height} = fm.sizeFor(style, text));
}
return new Rectangle(0,0,
padding.left() + padding.right() + width,
padding.top() + padding.bottom() + height);
}
textBoundsAllChunks() {
var fm = this._fontMetric || this.env.fontMetric,
padding = this.padding,
defaultStyle = this.textStyle,
lines = this.textAndAttributesOfLines,
defaultIsMonospaced = !fm.isProportional(defaultStyle.fontFamily),
{height: defaultHeight} = fm.sizeFor(defaultStyle, "x"),
height = 0, width = 0;
for (var i = 0; i < lines.length; i++) {
var textAndAttributes = lines[i];
// empty line
if (!textAndAttributes.length) { height += defaultHeight; continue; }
var lineHeight = 0, lineWidth = 0;
for (var j = 0; j < textAndAttributes.length; j = j+2) {
var text = textAndAttributes[j],
style = textAndAttributes[j+1] || {},
mergedStyle = {...defaultStyle, ...style},
isMonospaced = (defaultIsMonospaced && !style.fontFamily)
|| !fm.isProportional(mergedStyle.fontFamily);
if (isMonospaced) {
var fontId = mergedStyle.fontFamily + "-" + mergedStyle.fontSize,
{width: charWidth, height: charHeight} = fm.sizeFor(mergedStyle, "x");
lineWidth += text.length*charWidth;
lineHeight = Math.max(lineHeight, charHeight);
} else {
var {width: textWidth, height: textHeight} = fm.sizeFor(mergedStyle, text);
lineWidth += textWidth
lineHeight = Math.max(lineHeight, textHeight);
}
}
height += lineHeight;
width = Math.max(width, lineWidth);
}
return new Rectangle(0,0,
padding.left() + padding.right() + width,
padding.top() + padding.bottom() + height);
}
invalidateTextLayout() {
this._cachedTextBounds = null;
if (this.autofit) this._needsFit = true;
this.makeDirty();
}
textBounds() {
// this.env.fontMetric.sizeFor(style, string)
var {textAndAttributes, _cachedTextBounds} = this;
return _cachedTextBounds ? _cachedTextBounds :
this._cachedTextBounds = textAndAttributes.length <= 2 ?
this.textBoundsSingleChunk() : this.textBoundsAllChunks();
}
forceRerender() {
this._cachedTextBounds = null;
this.makeDirty();
}
applyLayoutIfNeeded() {
this.fitIfNeeded();
super.applyLayoutIfNeeded();
}
render(renderer) {
var renderedText = [],
nLines = this.textAndAttributesOfLines.length;
for (var i = 0; i < nLines; i++) {
var line = this.textAndAttributesOfLines[i];
for (var j = 0; j < line.length; j = j+2) {
var text = line[j],
style = line[j+1];
renderedText.push(this.renderChunk(text, style));
}
if (i < nLines-1) renderedText.push(h("br"));
}
var {
fontColor,
fontFamily,
fontSize,
fontStyle,
fontWeight,
textDecoration,
textStyleClasses,
} = this.textStyle,
padding = this.padding,
style = {
fontFamily,
fontSize: typeof fontSize === "number" ? fontSize + "px" : fontSize,
color: fontColor ? String(fontColor) : "transparent",
position: "absolute",
paddingLeft: padding.left() + "px",
paddingRight: padding.right() + "px",
paddingTop: padding.top() + "px",
paddingBottom: padding.bottom() + "px",
cursor: this.nativeCursor,
"white-space": "pre",
"word-break": "keep-all"
},
attrs = defaultAttributes(this, renderer);
if (fontWeight !== "normal") style.fontWeight = fontWeight;
if (fontStyle !== "normal") style.fontStyle = fontStyle;
if (textDecoration !== "none") style.textDecoration = textDecoration;
if (textStyleClasses && textStyleClasses.length)
attrs.className = (attrs.className || "") + " " + textStyleClasses.join(" ");
attrs.style = {...defaultStyle(this), ...style};
return h("div", attrs, [...renderedText, renderer.renderSubmorphs(this)]);
}
renderChunk(text, chunkStyle) {
chunkStyle = chunkStyle || {};
var {
backgroundColor,
fontColor,
fontFamily,
fontStyle,
fontWeight,
textDecoration,
textStyleClasses,
textAlign
} = chunkStyle,
style = {},
attrs = {style};
if (backgroundColor) style.backgroundColor = String(backgroundColor);
if (fontFamily) style.fontFamily = fontFamily;
if (fontColor) style.color = String(fontColor);
if (fontWeight !== "normal") style.fontWeight = fontWeight;
if (fontStyle !== "normal") style.fontStyle = fontStyle;
if (textDecoration !== "none") style.textDecoration = textDecoration;
if (textAlign) style.textAlign = textAlign;
if (textStyleClasses && textStyleClasses.length)
attrs.className = textStyleClasses.join(" ");
var lengthAttrs = ["fontSize", "width", "height", "maxWidth", "maxHeight", "top", "left", "padding", "paddingLeft", "paddingRight", "paddingBottom", "paddingTop"];
for (var i = 0; i < lengthAttrs.length; i++) {
var name = lengthAttrs[i];
if (!chunkStyle.hasOwnProperty(name)) continue;
var value = chunkStyle[name];
style[name] = typeof value === "number" ? value + "px" : value;
}
return h("span", attrs, text);
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// events
async interactivelyChangeLabel() {
let newLabel = await this.world().prompt("edit label", {
input: this.textString,
historyId: "lively.morphic-label-edit-hist"
});
if (typeof newLabel === "string")
this.textString = newLabel;
}
menuItems() {
let items = super.menuItems();
items.unshift({isDivider: true});
items.unshift(["change label", () => this.interactivelyChangeLabel()]);
return items;
}
}
| text/label.js | import { obj, arr, string, properties } from "lively.lang";
import { Rectangle, Color } from "lively.graphics";
import { Morph } from "../index.js";
import { defaultStyle, defaultAttributes } from "../rendering/morphic-default.js";
import { h } from "virtual-dom";
import { Icon, Icons } from "../components/icons.js";
import { signal } from "lively.bindings";
import { splitTextAndAttributesIntoLines } from "./attributes.js";
import { RichTextControl } from "./ui.js";
export class Label extends Morph {
static get properties() {
return {
fill: {defaultValue: Color.transparent},
draggable: {defaultValue: false},
nativeCursor: {defaultValue: "default"},
isIcon: {
derived: true,
get() {
return properties.values(Icons).map(({code}) => code).includes(this.textString)
}
},
value: {
derived: true, after: ["textAndAttributes", "textString"],
get() {
var {textAndAttributes} = this;
if (textAndAttributes.length <= 2) {
var [text, style] = textAndAttributes;
if (!Object.keys(style || {}).length) return text || "";
}
return textAndAttributes;
},
set(value) {
typeof value === "string" ?
this.textString = value :
this.textAndAttributes = value;
}
},
textString: {
derived: true, after: ["textAndAttributes"],
get() { return this.textAndAttributes.map((text, i) => i % 2==0 ? text : "").join(""); },
set(value) { this.textAndAttributes = [value, null]; }
},
textAndAttributes: {
get() {
var val = this.getProperty("textAndAttributes");
if (!val || val.length < 1) val = ["", null];
return val;
},
set(value) {
if (!Array.isArray(value)) value = [String(value), {}];
if (value.length === 0) value = ["", {}];
this._cachedTextBounds = null;
this.setProperty("textAndAttributes", value);
if (this.autofit) this._needsFit = true;
signal(this, "value", value);
}
},
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// valueAndAnnotation is a way to put rich text content followed by a right
// aligned annotation into a label. It simply is using textAndAttributes with
// the convention that the last string/attribue pair in textAndAttributes is the
// annotation (the attribute includes the textStyleClass "annotation")
valueAndAnnotation: {
derived: true, after: ["textAndAttributes"],
get() {
var value = this.textAndAttributes, annotation = null;
if (value.length > 2) {
var [string, props] = value.slice(-2);
if (props && props.textStyleClasses && props.textStyleClasses.includes("annotation")) {
value = value.slice(0, -2);
annotation = [string, props];
}
}
return {value, annotation};
},
set(valueAndAnnotation) {
var {value, annotation} = valueAndAnnotation;
// Ensure value is in the right format for being the prefix in textAndAttributes
if (!value) value = "";
if (typeof value === "string") value = [value, null]
if (!Array.isArray(value)) value = [String(value), null];
var textAndAttributes = value.slice();
// convert and add the annotation
if (annotation) {
if (typeof annotation === "string") annotation = [annotation, null];
var annAttr = annotation[1];
if (!annAttr) annAttr = annotation[1] = {};
textAndAttributes.push(...annotation);
annAttr.textStyleClasses = (annAttr.textStyleClasses || []).concat("annotation");
if (!annAttr.textStyleClasses.includes("annotation"))
annAttr.textStyleClasses.push("annotation");
}
this.textAndAttributes = textAndAttributes;
}
},
autofit: {
defaultValue: true,
set(value) {
this.setProperty("autofit", value);
if (value) this._needsFit = true;
}
},
padding: {
type: "Rectangle",
isStyleProp: true,
defaultValue: Rectangle.inset(0),
initialize(value) { this.padding = value; /*for num -> rect conversion*/},
set(value) {
if (!value) value = Rectangle.inset(0);
this._cachedTextBounds = null;
this.setProperty("padding", typeof value === "number" ? Rectangle.inset(value) : value);
if (this.autofit) this._needsFit = true;
}
},
fontFamily: {
isStyleProp: true,
type: "Enum",
values: RichTextControl.basicFontItems().map(f => f.value),
defaultValue: "Sans-Serif",
set(fontFamily) {
this._cachedTextBounds = null;
this.setProperty("fontFamily", fontFamily);
if (this.autofit) this._needsFit = true;
}
},
fontSize: {
type: "Number",
min: 1,
isStyleProp: true,
defaultValue: 12,
set(fontSize) {
this._cachedTextBounds = null;
this.setProperty("fontSize", fontSize);
if (this.autofit) this._needsFit = true;
}
},
fontColor: {type: "Color", isStyleProp: true, defaultValue: Color.black},
fontWeight: {
type: "Enum",
values: ["bold", "bolder", "light", "lighter"],
isStyleProp: true,
defaultValue: "normal",
set(fontWeight) {
this._cachedTextBounds = null;
this.setProperty("fontWeight", fontWeight);
if (this.autofit) this._needsFit = true;
}
},
fontStyle: {
type: "Enum",
values: ["normal", "italic", "oblique"],
isStyleProp: true,
defaultValue: "normal",
set(fontStyle) {
this._cachedTextBounds = null;
this.setProperty("fontStyle", fontStyle);
if (this.autofit) this._needsFit = true;
}
},
textDecoration: {defaultValue: "none"},
textStyleClasses: {
defaultValue: undefined,
set(textStyleClasses) {
this._cachedTextBounds = null;
this.setProperty("textStyleClasses", textStyleClasses);
if (this.autofit) this._needsFit = true;
}
}
}
}
static icon(iconName, props = {prefix: "", suffix: ""}) {
return Icon.makeLabel(iconName, props);
}
constructor(props = {}) {
var { fontMetric, position, rightCenter, leftCenter, topCenter,
bottom, top, right, left, bottomCenter, bottomLeft, bottomRight,
topRight, topLeft, center, extent } = props;
super(obj.dissoc(props, ["fontMetric"]));
if (fontMetric)
this._fontMetric = fontMetric;
this._cachedTextBounds = null;
this.fit();
// Update position + extent after fit
if (extent !== undefined) this.extent = extent;
if (position !== undefined) this.position = position;
if (rightCenter !== undefined) this.rightCenter = rightCenter;
if (leftCenter !== undefined) this.leftCenter = leftCenter;
if (topCenter !== undefined) this.topCenter = topCenter;
if (bottom !== undefined) this.bottom = bottom;
if (top !== undefined) this.top = top;
if (right !== undefined) this.right = right;
if (left !== undefined) this.left = left;
if (bottomCenter !== undefined) this.bottomCenter = bottomCenter;
if (bottomLeft !== undefined) this.bottomLeft = bottomLeft;
if (bottomRight !== undefined) this.bottomRight = bottomRight;
if (topRight !== undefined) this.topRight = topRight;
if (topLeft !== undefined) this.topLeft = topLeft;
if (center !== undefined) this.center = center;
}
get isLabel() { return true }
get textStyle() {
return obj.select(this, [
"textStyleClasses",
"textDecoration",
"fontStyle",
"fontWeight",
"fontColor",
"fontSize",
"fontFamily"
]);
}
fit() {
this.extent = this.textBounds().extent();
this._needsFit = false;
return this;
}
fitIfNeeded() {
if (this._needsFit) { this.fit(); }
}
get textAndAttributesOfLines() {
return splitTextAndAttributesIntoLines(this.textAndAttributes, "\n");
}
textBoundsSingleChunk() {
// text bounds not considering "chunks", i.e. only default text style is
// used
var fm = this._fontMetric || this.env.fontMetric,
[text, chunkStyle] = this.textAndAttributes,
style = {...this.textStyle, ...chunkStyle},
padding = this.padding,
width, height;
if (!fm.isProportional(style.fontFamily)) {
var {width: charWidth, height: charHeight} = fm.sizeFor(style, "x");
width = text.length * charWidth;
height = charHeight;
} else {
({width, height} = fm.sizeFor(style, text));
}
return new Rectangle(0,0,
padding.left() + padding.right() + width,
padding.top() + padding.bottom() + height);
}
textBoundsAllChunks() {
var fm = this._fontMetric || this.env.fontMetric,
padding = this.padding,
defaultStyle = this.textStyle,
lines = this.textAndAttributesOfLines,
defaultIsMonospaced = !fm.isProportional(defaultStyle.fontFamily),
{height: defaultHeight} = fm.sizeFor(defaultStyle, "x"),
height = 0, width = 0;
for (var i = 0; i < lines.length; i++) {
var textAndAttributes = lines[i];
// empty line
if (!textAndAttributes.length) { height += defaultHeight; continue; }
var lineHeight = 0, lineWidth = 0;
for (var j = 0; j < textAndAttributes.length; j = j+2) {
var text = textAndAttributes[j],
style = textAndAttributes[j+1] || {},
mergedStyle = {...defaultStyle, ...style},
isMonospaced = (defaultIsMonospaced && !style.fontFamily)
|| !fm.isProportional(mergedStyle.fontFamily);
if (isMonospaced) {
var fontId = mergedStyle.fontFamily + "-" + mergedStyle.fontSize,
{width: charWidth, height: charHeight} = fm.sizeFor(mergedStyle, "x");
lineWidth += text.length*charWidth;
lineHeight = Math.max(lineHeight, charHeight);
} else {
var {width: textWidth, height: textHeight} = fm.sizeFor(mergedStyle, text);
lineWidth += textWidth
lineHeight = Math.max(lineHeight, textHeight);
}
}
height += lineHeight;
width = Math.max(width, lineWidth);
}
return new Rectangle(0,0,
padding.left() + padding.right() + width,
padding.top() + padding.bottom() + height);
}
invalidateTextLayout() {
this._cachedTextBounds = null;
if (this.autofit) this._needsFit = true;
this.makeDirty();
}
textBounds() {
// this.env.fontMetric.sizeFor(style, string)
var {textAndAttributes, _cachedTextBounds} = this;
return _cachedTextBounds ? _cachedTextBounds :
this._cachedTextBounds = textAndAttributes.length <= 2 ?
this.textBoundsSingleChunk() : this.textBoundsAllChunks();
}
forceRerender() {
this._cachedTextBounds = null;
this.makeDirty();
}
applyLayoutIfNeeded() {
this.fitIfNeeded();
super.applyLayoutIfNeeded();
}
render(renderer) {
var renderedText = [],
nLines = this.textAndAttributesOfLines.length;
for (var i = 0; i < nLines; i++) {
var line = this.textAndAttributesOfLines[i];
for (var j = 0; j < line.length; j = j+2) {
var text = line[j],
style = line[j+1];
renderedText.push(this.renderChunk(text, style));
}
if (i < nLines-1) renderedText.push(h("br"));
}
var {
fontColor,
fontFamily,
fontSize,
fontStyle,
fontWeight,
textDecoration,
textStyleClasses,
} = this.textStyle,
padding = this.padding,
style = {
fontFamily,
fontSize: typeof fontSize === "number" ? fontSize + "px" : fontSize,
color: fontColor ? String(fontColor) : "transparent",
position: "absolute",
paddingLeft: padding.left() + "px",
paddingRight: padding.right() + "px",
paddingTop: padding.top() + "px",
paddingBottom: padding.bottom() + "px",
cursor: this.nativeCursor,
"white-space": "pre",
"word-break": "keep-all"
},
attrs = defaultAttributes(this, renderer);
if (fontWeight !== "normal") style.fontWeight = fontWeight;
if (fontStyle !== "normal") style.fontStyle = fontStyle;
if (textDecoration !== "none") style.textDecoration = textDecoration;
if (textStyleClasses && textStyleClasses.length)
attrs.className = (attrs.className || "") + " " + textStyleClasses.join(" ");
attrs.style = {...defaultStyle(this), ...style};
return h("div", attrs, [...renderedText, renderer.renderSubmorphs(this)]);
}
renderChunk(text, chunkStyle) {
chunkStyle = chunkStyle || {};
var {
backgroundColor,
fontColor,
fontFamily,
fontStyle,
fontWeight,
textDecoration,
textStyleClasses,
textAlign
} = chunkStyle,
style = {},
attrs = {style};
if (backgroundColor) style.backgroundColor = String(backgroundColor);
if (fontFamily) style.fontFamily = fontFamily;
if (fontColor) style.color = String(fontColor);
if (fontWeight !== "normal") style.fontWeight = fontWeight;
if (fontStyle !== "normal") style.fontStyle = fontStyle;
if (textDecoration !== "none") style.textDecoration = textDecoration;
if (textAlign) style.textAlign = textAlign;
if (textStyleClasses && textStyleClasses.length)
attrs.className = textStyleClasses.join(" ");
var lengthAttrs = ["fontSize", "width", "height", "maxWidth", "maxHeight", "top", "left", "padding", "paddingLeft", "paddingRight", "paddingBottom", "paddingTop"];
for (var i = 0; i < lengthAttrs.length; i++) {
var name = lengthAttrs[i];
if (!chunkStyle.hasOwnProperty(name)) continue;
var value = chunkStyle[name];
style[name] = typeof value === "number" ? value + "px" : value;
}
return h("span", attrs, text);
}
}
| label menu items
| text/label.js | label menu items | <ide><path>ext/label.js
<ide>
<ide> return h("span", attrs, text);
<ide> }
<add>
<add> // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
<add> // events
<add>
<add> async interactivelyChangeLabel() {
<add> let newLabel = await this.world().prompt("edit label", {
<add> input: this.textString,
<add> historyId: "lively.morphic-label-edit-hist"
<add> });
<add> if (typeof newLabel === "string")
<add> this.textString = newLabel;
<add> }
<add>
<add> menuItems() {
<add> let items = super.menuItems();
<add> items.unshift({isDivider: true});
<add> items.unshift(["change label", () => this.interactivelyChangeLabel()]);
<add> return items;
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | 6077ba19c2d40ce23cf9160e3b42af49ddb67dd2 | 0 | anylineorg/anyline,anylineorg/anyline | /*
* Copyright 2006-2022 www.anyline.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package org.anyline.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XssUtil {
private static List<Pattern> patterns = new ArrayList<Pattern>();
static {
List<Object[]> regexps = new ArrayList<Object[]>();
regexps.add(new Object[] { "<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE });
regexps.add(new Object[] { "eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
regexps.add(new Object[] { "expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
regexps.add(new Object[] { "(javascript:|vbscript:|view-source:)*", Pattern.CASE_INSENSITIVE });
regexps.add(new Object[] { "<(no)?iframe[^>]*>.*?</(no)?iframe>", Pattern.CASE_INSENSITIVE });
regexps.add(new Object[] { "<(no)?iframe[^>]*>", Pattern.CASE_INSENSITIVE });
//regexps.add(new Object[] { "<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
regexps.add(new Object[] {"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
regexps.add(new Object[] {"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
String regex = null;
Integer flag = null;
int arrLength = 0;
for (Object[] arr : regexps) {
arrLength = arr.length;
for (int i = 0; i < arrLength; i++) {
regex = (String) arr[0];
flag = (Integer) arr[1];
patterns.add(Pattern.compile(regex, flag));
}
}
}
/**
* 过滤字符
* @param value value
* @return String
*/
public static String strip(String value) {
if (BasicUtil.isNotEmpty(value)) {
Matcher matcher = null;
for (Pattern pattern : patterns) {
matcher = pattern.matcher(value);
if (matcher.find()) {
value = matcher.replaceAll("");
}
}
//value = value.replaceAll("<", "<").replaceAll(">", ">");
}
return value;
}
/**
* 检测是否存在非法字符 通过(没有非法字条)返回true
* @param value value
* @return boolean
*/
public static boolean check(String value) {
if (BasicUtil.isNotEmpty(value)) {
Matcher matcher = null;
for (Pattern pattern : patterns) {
matcher = pattern.matcher(value);
if (matcher.find()) {
return false;
}
}
}
return true;
}
}
| anyline-core/src/main/java/org/anyline/util/XssUtil.java | /*
* Copyright 2006-2022 www.anyline.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package org.anyline.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XssUtil {
private static List<Pattern> patterns = new ArrayList<Pattern>();
static {
List<Object[]> regexps = new ArrayList<Object[]>();
regexps.add(new Object[] { "<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE });
regexps.add(new Object[] { "eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
regexps.add(new Object[] { "expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
regexps.add(new Object[] { "(javascript:|vbscript:|view-source:)*", Pattern.CASE_INSENSITIVE });
regexps.add(new Object[] { "<(no)?iframe[^>]*>.*?</(no)?iframe>", Pattern.CASE_INSENSITIVE });
regexps.add(new Object[] { "<(no)?iframe[^>]*>", Pattern.CASE_INSENSITIVE });
//regexps.add(new Object[] { "<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
regexps.add(new Object[] {"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
regexps.add(new Object[] {"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
String regex = null;
Integer flag = null;
int arrLength = 0;
for (Object[] arr : regexps) {
arrLength = arr.length;
for (int i = 0; i < arrLength; i++) {
regex = (String) arr[0];
flag = (Integer) arr[1];
patterns.add(Pattern.compile(regex, flag));
}
}
}
/**
* 过滤字符
* @param value value
* @return return
*/
public static String strip(String value) {
if (BasicUtil.isNotEmpty(value)) {
Matcher matcher = null;
for (Pattern pattern : patterns) {
matcher = pattern.matcher(value);
if (matcher.find()) {
value = matcher.replaceAll("");
}
}
//value = value.replaceAll("<", "<").replaceAll(">", ">");
}
return value;
}
/**
* 检测是否存在非法字符 通过(没有非法字条)返回true
* @param value value
* @return return
*/
public static boolean check(String value) {
if (BasicUtil.isNotEmpty(value)) {
Matcher matcher = null;
for (Pattern pattern : patterns) {
matcher = pattern.matcher(value);
if (matcher.find()) {
return false;
}
}
}
return true;
}
}
| XssUtil
| anyline-core/src/main/java/org/anyline/util/XssUtil.java | XssUtil | <ide><path>nyline-core/src/main/java/org/anyline/util/XssUtil.java
<ide> /**
<ide> * 过滤字符
<ide> * @param value value
<del> * @return return
<add> * @return String
<ide> */
<ide> public static String strip(String value) {
<ide> if (BasicUtil.isNotEmpty(value)) {
<ide> /**
<ide> * 检测是否存在非法字符 通过(没有非法字条)返回true
<ide> * @param value value
<del> * @return return
<add> * @return boolean
<ide> */
<ide> public static boolean check(String value) {
<ide> if (BasicUtil.isNotEmpty(value)) { |
|
JavaScript | mit | 6f1f93d31175039ebf6b54dafdc21ecb45211db6 | 0 | AlexMasterov/webpack-kit,AlexMasterov/webpack-kit | const { resolve } = require('path');
const { isProd, isDev } = require('./webpack/env');
let config = {
devtool: 'cheap-module-eval-source-map',
cache: true,
performance: {
hints: false,
},
context: resolve(__dirname, 'src'),
entry: {
bundle: [
'./index.js',
],
vendor: [
'react',
'react-dom',
],
},
output: {
pathinfo: isDev,
publicPath: '/',
path: resolve(__dirname, 'dist'),
filename: 'js/[name]-[chunkhash:8].js',
chunkFilename: 'js/[name]-[chunkhash:8].chunk.js',
devtoolModuleFilenameTemplate: ({ absoluteResourcePath }) =>
resolve(absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
alias: {},
extensions: [],
modules: [
resolve(__dirname, 'src'),
'node_modules',
],
},
plugins: [],
module: {
rules: [],
},
};
// Context
config = require('./webpack/stats')(config);
// Modules
config = require('./webpack/modules/noParse')(config);
config = require('./webpack/modules/babel')(config);
config = require('./webpack/modules/css')(config);
config = require('./webpack/modules/urlFont')(config);
config = require('./webpack/modules/urlImage')(config);
config = require('./webpack/modules/urlVideo')(config);
// Plugins
config = require('./webpack/plugins/define')(config);
config = require('./webpack/plugins/hash')(config);
if (isProd) {
config.devtool = 'source-map';
// Context
config = require('./webpack/perf')(config);
config = require('./webpack/node')(config);
// Plugins
config = require('./webpack/plugins/clean')(config);
config = require('./webpack/plugins/manifest')(config);
config = require('./webpack/plugins/commonsChunk')(config);
config = require('./webpack/plugins/moduleConcat')(config);
config = require('./webpack/plugins/uglify')(config);
config = require('./webpack/plugins/optimizeCss')(config);
}
module.exports = config;
| webpack.config.js | const { resolve } = require('path');
const { isProd, isDev } = require('./webpack/env');
let config = {
devtool: 'cheap-module-eval-source-map',
cache: true,
performance: {
hints: false,
},
context: resolve(__dirname, 'src'),
entry: {
bundle: [
'./index.js',
],
vendor: [
'react',
'react-dom',
],
},
output: {
pathinfo: isDev,
publicPath: '/',
path: resolve(__dirname, 'dist'),
filename: 'js/[name]-[chunkhash:8].js',
chunkFilename: 'js/[name]-[chunkhash:8].chunk.js',
},
resolve: {
alias: {},
extensions: [],
modules: [
resolve(__dirname, 'src'),
'node_modules',
],
},
plugins: [],
module: {
rules: [],
},
};
// Context
config = require('./webpack/stats')(config);
// Modules
config = require('./webpack/modules/noParse')(config);
config = require('./webpack/modules/babel')(config);
config = require('./webpack/modules/css')(config);
config = require('./webpack/modules/urlFont')(config);
config = require('./webpack/modules/urlImage')(config);
config = require('./webpack/modules/urlVideo')(config);
// Plugins
config = require('./webpack/plugins/define')(config);
config = require('./webpack/plugins/hash')(config);
if (isProd) {
config.devtool = 'source-map';
// Context
config = require('./webpack/perf')(config);
config = require('./webpack/node')(config);
// Plugins
config = require('./webpack/plugins/clean')(config);
config = require('./webpack/plugins/manifest')(config);
config = require('./webpack/plugins/commonsChunk')(config);
config = require('./webpack/plugins/moduleConcat')(config);
config = require('./webpack/plugins/uglify')(config);
config = require('./webpack/plugins/optimizeCss')(config);
}
module.exports = config;
| Add devtoolModuleFilenameTemplate option
Point sourcemap entries to original disk location (format as URL on Windows).
| webpack.config.js | Add devtoolModuleFilenameTemplate option | <ide><path>ebpack.config.js
<ide> path: resolve(__dirname, 'dist'),
<ide> filename: 'js/[name]-[chunkhash:8].js',
<ide> chunkFilename: 'js/[name]-[chunkhash:8].chunk.js',
<add> devtoolModuleFilenameTemplate: ({ absoluteResourcePath }) =>
<add> resolve(absoluteResourcePath).replace(/\\/g, '/'),
<ide> },
<ide>
<ide> resolve: { |
|
Java | apache-2.0 | 814cf5efaff86720c3895d91ed557b03c9ca0ebb | 0 | OpenHFT/Chronicle-Queue,OpenHFT/Chronicle-Queue | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.*;
import net.openhft.chronicle.bytes.util.DecoratedBufferUnderflowException;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.pool.StringBuilderPool;
import net.openhft.chronicle.core.time.TimeProvider;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.*;
import net.openhft.chronicle.wire.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.nio.BufferOverflowException;
import java.text.ParseException;
import static net.openhft.chronicle.queue.TailerDirection.*;
import static net.openhft.chronicle.queue.TailerState.*;
import static net.openhft.chronicle.queue.impl.single.ScanResult.*;
import static net.openhft.chronicle.wire.BinaryWireCode.FIELD_NUMBER;
public class SingleChronicleQueueExcerpts {
private static final Logger LOG = LoggerFactory.getLogger(SingleChronicleQueueExcerpts.class);
private static final int MESSAGE_HISTORY_METHOD_ID = -1;
private static StringBuilderPool SBP = new StringBuilderPool();
private static void releaseWireResources(final Wire wire) {
StoreComponentReferenceHandler.queueForRelease(wire);
}
// *************************************************************************
//
// APPENDERS
//
// *************************************************************************
@FunctionalInterface
interface WireWriter<T> {
void write(T message, WireOut wireOut);
}
public interface InternalAppender {
void writeBytes(long index, BytesStore bytes);
}
static class StoreAppender implements ExcerptAppender, ExcerptContext, InternalAppender {
private static final long PRETOUCHER_PREROLL_TIME_MS = 2_000L;
private final TimeProvider pretouchTimeProvider;
private WireStore pretouchStore;
private int pretouchCycle;
static final int REPEAT_WHILE_ROLLING = 128;
@NotNull
private final SingleChronicleQueue queue;
@NotNull
private final StoreAppenderContext context;
private final ClosableResources closableResources;
@NotNull
private final HeaderWriteStrategy headerWriteStrategy;
private final WireStorePool storePool;
@Nullable
WireStore store;
private int cycle = Integer.MIN_VALUE;
@Nullable
private Wire wire;
@Nullable
private Wire bufferWire; // if you have a buffered write.
@Nullable
private Wire wireForIndex;
private long position = 0;
@Nullable
private volatile Thread appendingThread = null;
private long lastIndex = Long.MIN_VALUE;
private boolean lazyIndexing = false;
private long lastPosition;
private int lastCycle;
@Nullable
private PretoucherState pretoucher = null;
private Padding padToCacheLines = Padding.SMART;
StoreAppender(@NotNull SingleChronicleQueue queue, boolean progressOnContention, @NotNull WireStorePool storePool) {
this.queue = queue;
queue.addCloseListener(this, StoreAppender::close);
context = new StoreAppenderContext();
this.storePool = storePool;
closableResources = new ClosableResources(queue);
queue.ensureThatRollCycleDoesNotConflictWithExistingQueueFiles();
headerWriteStrategy = progressOnContention ? new HeaderWriteStrategyDefer() : new HeaderWriteStrategyOriginal();
pretouchTimeProvider = () -> queue.time().currentTimeMillis() + PRETOUCHER_PREROLL_TIME_MS;
}
@NotNull
public WireStore store() {
if (store == null)
setCycle(cycle());
return store;
}
@Override
@NotNull
public Padding padToCacheAlignMode() {
return padToCacheLines;
}
/**
* @param padToCacheLines the default for chronicle queue is Padding.SMART, which
* automatically pads all method calls other than {@link
* StoreAppender#writeBytes(net.openhft.chronicle.bytes.WriteBytesMarshallable)}
* and {@link StoreAppender#writeText(java.lang.CharSequence)}.
* Which can not be padded with out changing the message format, The
* reason we pad is to ensure that a message header does not straggle
* a cache line.
*/
@Override
public void padToCacheAlign(Padding padToCacheLines) {
this.padToCacheLines = padToCacheLines;
}
/**
* @param marshallable to write to excerpt.
*/
@Override
public void writeBytes(@NotNull WriteBytesMarshallable marshallable) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
marshallable.writeMarshallable(dc.wire().bytes());
if (padToCacheAlignMode() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
@Override
public void writeText(@NotNull CharSequence text) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
dc.wire().bytes()
.append8bit(text);
if (padToCacheAlignMode() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
void close() {
Wire w0 = wireForIndex;
wireForIndex = null;
if (w0 != null)
w0.bytes().release();
Wire w = wire;
wire = null;
if (w != null) {
w.bytes().release();
}
releasePretouchStore();
if (store != null) {
storePool.release(store);
}
if (bufferWire != null) {
bufferWire.bytes().release();
bufferWire = null;
}
store = null;
storePool.close();
}
/**
* this method NOT thread safe
*/
@Override
public void pretouch() {
if (queue.isClosed())
throw new RuntimeException("Queue Closed");
try {
int qCycle = queue.cycle();
setCycle(qCycle);
if (pretoucher == null)
pretoucher = new PretoucherState(this.store::writePosition);
Wire wire = this.wire;
if (wire != null)
pretoucher.pretouch((MappedBytes) wire.bytes());
if (pretouchStore != null && pretouchCycle == qCycle) {
releasePretouchStore();
return;
}
int pretouchCycle0 = queue.cycle(pretouchTimeProvider);
if (pretouchCycle0 != qCycle && pretouchCycle != pretouchCycle0) {
releasePretouchStore();
pretouchStore = queue.storeSupplier().acquire(pretouchCycle0, true);
pretouchCycle = pretouchCycle0;
pretoucher = null;
if (Jvm.isDebugEnabled(getClass()))
Jvm.debug().on(getClass(), "Pretoucher ROLLING to next file=" +
pretouchStore.file());
}
} catch (Throwable e) {
Jvm.warn().on(getClass(), e);
}
}
private void releasePretouchStore() {
WireStore pretouchStore = this.pretouchStore;
if (pretouchStore == null)
return;
pretouchStore.release();
pretouchCycle = -1;
this.pretouchStore = null;
}
@Nullable
@Override
public Wire wire() {
return wire;
}
@Nullable
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
void lastIndex(long index) {
this.lastIndex = index;
}
@NotNull
@Override
public ExcerptAppender lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
try {
resetPosition();
} catch (EOFException ex) {
throw new IllegalStateException("EOF found");
}
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public boolean recordHistory() {
return sourceId() != 0;
}
void setCycle(int cycle) {
if (cycle != this.cycle)
setCycle2(cycle, true);
}
private void setCycle2(int cycle, boolean createIfAbsent) {
if (cycle < 0)
throw new IllegalArgumentException("You can not have a cycle that starts " +
"before Epoch. cycle=" + cycle);
SingleChronicleQueue queue = this.queue;
if (this.store != null) {
storePool.release(this.store);
}
this.store = storePool.acquire(cycle, queue.epoch(), createIfAbsent);
closableResources.storeReference = store;
resetWires(queue);
// only set the cycle after the wire is set.
this.cycle = cycle;
assert wire.startUse();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
try {
resetPosition();
queue.onRoll(cycle);
} catch (EOFException eof) {
handleRoll(cycle);
}
}
private void resetWires(@NotNull SingleChronicleQueue queue) {
WireType wireType = queue.wireType();
{
Wire oldw = this.wire;
this.wire = wireType.apply(store.bytes());
closableResources.wireReference = this.wire.bytes();
if (oldw != null) {
releaseWireResources(oldw);
}
}
{
Wire old = this.wireForIndex;
this.wireForIndex = wireType.apply(store.bytes());
closableResources.wireForIndexReference = wireForIndex.bytes();
if (old != null) {
releaseWireResources(old);
}
}
}
private void resetPosition() throws UnrecoverableTimeoutException, EOFException {
try {
if (store == null || wire == null)
return;
position(store.writePosition());
Bytes<?> bytes = wire.bytes();
int header = bytes.readVolatileInt(position);
if (header == Wires.END_OF_DATA) {
throw new EOFException();
}
assert position == 0 || Wires.isReadyData(header);
bytes.writePosition(position + 4 + Wires.lengthOf(header));
if (lazyIndexing) {
wire.headerNumber(Long.MIN_VALUE);
return;
}
final long headerNumber = store.sequenceForPosition(this, position, true);
wire.headerNumber(queue.rollCycle().toIndex(cycle, headerNumber + 1) - 1);
assert lazyIndexing || wire.headerNumber() != -1 || checkIndex(wire.headerNumber(), position);
} catch (@NotNull BufferOverflowException | StreamCorruptedException e) {
throw new AssertionError(e);
}
assert checkWritePositionHeaderNumber();
}
@NotNull
@Override
public DocumentContext writingDocument(boolean metaData) throws UnrecoverableTimeoutException {
assert checkAppendingThread();
assert checkWritePositionHeaderNumber();
if (queue.isClosed.get())
throw new IllegalStateException("Queue is closed");
if (Thread.currentThread().isInterrupted())
throw new IllegalStateException("Queue won't write from an interrupted thread");
boolean ok = false;
try {
int cycle = queue.cycle();
if (wire == null) {
// we have check it the queue file has rolled due to an early EOF
cycle = Math.max(queue.lastCycle(), cycle);
setCycle2(cycle, true);
} else if (this.cycle != cycle)
rollCycleTo(cycle);
int safeLength = (int) queue.overlapSize();
ok = headerWriteStrategy.onContextOpen(metaData, safeLength);
return context;
} finally {
assert ok || resetAppendingThread();
}
}
private int handleRoll(int cycle) {
assert !((AbstractWire) wire).isInsideHeader();
int qCycle = queue.cycle();
if (cycle < queue.cycle()) {
setCycle2(cycle = qCycle, true);
} else if (cycle == qCycle) {
// for the rare case where the qCycle has just changed in the last
// few milliseconds since
setCycle2(++cycle, true);
} else {
throw new IllegalStateException("Found an EOF on the next cycle file," +
" this next file, should not have an EOF as its cycle " +
"number is greater than the current cycle (based on the " +
"current time), this should only happen " +
"if it was written by a different appender set with a different " +
"EPOCH or different roll cycle." +
"All your appenders ( that write to a given directory ) " +
"should have the same EPOCH and roll cycle" +
" qCycle=" + qCycle + ", cycle=" + cycle + ", queue-file=" + queue.fileAbsolutePath());
}
return cycle;
}
boolean checkWritePositionHeaderNumber() {
if (wire == null || wire.headerNumber() == Long.MIN_VALUE) return true;
try {
long pos1 = position;
/*
long posMax = store.writePosition();
if (pos1 > posMax+4) {
System.out.println(queue.dump());
String message = "########### " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" posMax: " + posMax;
System.err.println(message);
throw new AssertionError(message);
}*/
long seq1 = queue.rollCycle().toSequenceNumber(wire.headerNumber() + 1) - 1;
long seq2 = store.sequenceForPosition(this, pos1, true);
if (seq1 != seq2) {
// System.out.println(queue.dump());
String message = "~~~~~~~~~~~~~~ " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" seq1: " + seq1 +
" seq2: " + seq2;
System.err.println(message);
throw new AssertionError(message);
}
} catch (IOException e) {
Jvm.fatal().on(getClass(), e);
throw Jvm.rethrow(e);
}
return true;
}
@NotNull
@Override
public DocumentContext writingDocument(long index) {
context.isClosed = false;
assert checkAppendingThread();
context.wire = acquireBufferWire();
context.wire.headerNumber(index);
context.isClosed = false;
return context;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public void writeBytes(@NotNull BytesStore bytes) throws UnrecoverableTimeoutException {
append((m, w) -> w.bytes().write(m), bytes);
}
@NotNull
Wire acquireBufferWire() {
if (bufferWire == null) {
bufferWire = queue.wireType().apply(Bytes.elasticByteBuffer());
closableResources.bufferWireReference = bufferWire.bytes();
} else {
bufferWire.clear();
}
return bufferWire;
}
/**
* Write bytes at an index, but only if the index is at the end of the chronicle.
* If index is after the end of the chronicle, throw an IllegalStateException. If the
* index is before the end of the chronicle then do not change the state of the chronicle.
* <p>Thread-safe</p>
*
* @param index index to write at. Only if index is at the end of the chronicle will the bytes get written
* @param bytes payload
*/
public void writeBytes(long index, @NotNull BytesStore bytes) {
if (queue.isClosed.get())
throw new IllegalStateException("Queue is closed");
int cycle = queue.rollCycle().toCycle(index);
if (wire == null)
setCycle2(cycle, true);
else if (this.cycle != cycle)
rollCycleTo(cycle);
int safeLength = (int) queue.overlapSize();
assert checkAppendingThread();
try {
long pos = wire.bytes().writePosition();
// opening the context locks the chronicle
headerWriteStrategy.onContextOpen(false, safeLength);
boolean rollbackDontClose = index != wire.headerNumber() + 1;
if (rollbackDontClose) {
wire.bytes().writeSkip(-4);
wire.bytes().writeVolatileInt(wire.bytes().writePosition(), 0);
wire.bytes().writeLimit(wire.bytes().capacity());
this.position = pos;
((AbstractWire) wire).forceNotInsideHeader();
if (index > wire.headerNumber() + 1)
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue");
// TODO: assert bytes.equalBytes(wire.bytes() ...);
Jvm.warn().on(getClass(), "Trying to overwrite index " + Long.toHexString(index) + " which is before the end of the queue");
return;
}
try {
context.wire().bytes().write(bytes);
} finally {
context.close();
}
} finally {
this.appendingThread = null;
context.isClosed = true;
}
}
private void position(long position) {
// did the position jump too far forward.
if (position > store.writePosition() + queue.blockSize())
throw new IllegalArgumentException("pos: " + position + ", store.writePosition()=" +
store.writePosition() + " queue.blockSize()=" + queue.blockSize());
// System.err.println("----- "+Thread.currentThread().getName()+" pos: "+position);
this.position = position;
}
@Override
public long lastIndexAppended() {
if (lastIndex != Long.MIN_VALUE)
return lastIndex;
if (lastPosition == Long.MIN_VALUE || wire == null) {
throw new IllegalStateException("nothing has been appended, so there is no last index");
}
try {
long sequenceNumber = store.sequenceForPosition(this, lastPosition, true);
long index = queue.rollCycle().toIndex(lastCycle, sequenceNumber);
lastIndex(index);
return index;
} catch (Exception e) {
throw Jvm.rethrow(e);
}
}
@Override
public int cycle() {
if (cycle == Integer.MIN_VALUE) {
int cycle = this.queue.lastCycle();
if (cycle < 0)
cycle = queue.cycle();
setCycle2(cycle, true);
}
return cycle;
}
@Override
@NotNull
public SingleChronicleQueue queue() {
return queue;
}
@Override
public Runnable getCloserJob() {
return closableResources::releaseResources;
}
/**
* overwritten in delta wire
*
* @param wire
* @param index
*/
void beforeAppend(Wire wire, long index) {
}
private <T> void append(@NotNull WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException {
assert checkAppendingThread();
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
try {
position(store.writeHeader(wire, (int) queue.overlapSize(), timeoutMS()));
assert ((AbstractWire) wire).isInsideHeader();
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(position, false);
lastIndex(wire.headerNumber());
lastPosition = position;
lastCycle = cycle;
store.writePosition(position);
writeIndexForPosition(lastIndex, position);
} catch (EOFException theySeeMeRolling) {
try {
append2(wireWriter, writer);
} catch (EOFException e) {
throw new AssertionError(e);
}
}
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
assert resetAppendingThread();
}
}
private void rollCycleTo(int cycle) throws UnrecoverableTimeoutException {
if (wire != null) {
// only a valid check if the wire was set.
if (this.cycle == cycle)
throw new AssertionError();
store.writeEOF(wire, timeoutMS());
}
setCycle2(cycle, true);
}
/**
* Write an EOF marker on the current cycle if it is about to roll. It would do this any way
* if a new message was written, but this doesn't create a new cycle or add a message.
*/
public void writeEndOfCycleIfRequired() {
if (wire != null && queue.cycle() != cycle) {
store.writeEOF(wire, timeoutMS());
}
}
<T> void append2(@NotNull WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException, EOFException, StreamCorruptedException {
setCycle(Math.max(queue.cycle(), cycle + 1));
position(store.writeHeader(wire, (int) queue.overlapSize(), timeoutMS()));
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(position, false);
}
private boolean checkAppendingThread() {
Thread appendingThread = this.appendingThread;
Thread currentThread = Thread.currentThread();
if (appendingThread != null) {
if (appendingThread == currentThread)
throw new IllegalStateException("Nested blocks of writingDocument() not supported");
throw new IllegalStateException("Attempting to use Appender in " + currentThread + " while used by " + appendingThread);
}
this.appendingThread = currentThread;
return true;
}
private boolean resetAppendingThread() {
if (this.appendingThread == null)
throw new IllegalStateException("Attempting to release Appender in " + Thread.currentThread() + " but already released");
this.appendingThread = null;
return true;
}
void writeIndexForPosition(long index, long position)
throws UnrecoverableTimeoutException, StreamCorruptedException {
if (!lazyIndexing) {
long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
store.setPositionForSequenceNumber(this, sequenceNumber, position);
}
}
boolean checkIndex(long index, long position) {
try {
final long seq1 = queue.rollCycle().toSequenceNumber(index + 1) - 1;
final long seq2 = store.sequenceForPosition(this, position, true);
if (seq1 != seq2) {
final long seq3 = ((SingleChronicleQueueStore) store).indexing
.linearScanByPosition(wireForIndex(), position, 0, 0, true);
System.out.println("Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + Long.toHexString(seq1) +
" seq2: " + Long.toHexString(seq2) +
" seq3: " + Long.toHexString(seq3));
System.out.println(store.dump());
assert seq1 == seq3 : "seq1=" + seq1 + ", seq3=" + seq3;
assert seq1 == seq2 : "seq1=" + seq1 + ", seq2=" + seq2;
} else {
/* System.out.println("checked Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + seq1);*/
}
} catch (@NotNull EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
}
return true;
}
@Override
public String toString() {
return "StoreAppender{" +
"queue=" + queue +
", cycle=" + cycle +
", position=" + position +
", lastIndex=" + lastIndex +
", lazyIndexing=" + lazyIndexing +
", lastPosition=" + lastPosition +
", lastCycle=" + lastCycle +
'}';
}
private interface HeaderWriteStrategy {
void onContextClose();
boolean onContextOpen(boolean metaData, int safeLength);
}
class StoreAppenderContext implements DocumentContext {
boolean isClosed;
boolean deferredHeader;
boolean padToCacheAlign = true;
private boolean metaData = false;
private boolean rollbackOnClose = false;
@Nullable
private Wire wire;
@Override
public int sourceId() {
return StoreAppender.this.sourceId();
}
@Override
public boolean isPresent() {
return false;
}
@NotNull
@Override
public Wire wire() {
return wire;
}
@Override
public boolean isMetaData() {
return metaData;
}
@Override
public void metaData(boolean metaData) {
this.metaData = metaData;
}
@Override
public boolean isClosed() {
return isClosed;
}
/**
* Call this if you have detected an error condition and you want the context
* rolled back when it is closed, rather than committed
*/
@Override
public void rollbackOnClose() {
this.rollbackOnClose = true;
}
@Override
public void close() {
if (isClosed) {
LOG.warn("Already Closed, close was called twice.");
return;
}
try {
final boolean interrupted = Thread.currentThread().isInterrupted();
if (rollbackOnClose || interrupted) {
if (interrupted)
LOG.warn("Thread is interrupted. Can't guarantee complete message, so not committing");
// zero out all contents...
for (long i = position + Wires.SPB_HEADER_SIZE; i <= wire.bytes().writePosition(); i++)
wire.bytes().writeByte(i, (byte) 0);
// ...and then the header, as if we had never been here
wire.bytes().writeVolatileInt(position, 0);
wire.bytes().writePosition(position);
((AbstractWire) wire).forceNotInsideHeader();
return;
}
headerWriteStrategy.onContextClose();
if (wire == StoreAppender.this.wire) {
if (padToCacheAlign)
wire.padToCacheAlign();
boolean updatedHeader = false;
for (int i = 0; i < REPEAT_WHILE_ROLLING; i++) {
try {
wire.updateHeader(position, metaData);
updatedHeader = true;
break;
} catch (EOFException theySeeMeRolling) {
cycle = handleRoll(cycle);
}
}
if (!updatedHeader)
throw new IllegalStateException("Unable to roll to the current cycle");
lastPosition = position;
lastCycle = cycle;
if (!metaData) {
lastIndex(wire.headerNumber());
store.writePosition(position);
if (lastIndex != Long.MIN_VALUE)
writeIndexForPosition(lastIndex, position);
else
assert lazyIndexing || lastIndex == Long.MIN_VALUE || checkIndex(lastIndex, position);
}
assert checkWritePositionHeaderNumber();
} else if (wire != null) {
isClosed = true;
assert resetAppendingThread();
writeBytes(wire.headerNumber(), wire.bytes());
wire = StoreAppender.this.wire;
}
} catch (@NotNull StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
} finally {
assert isClosed || resetAppendingThread();
}
}
@Override
public long index() throws IORuntimeException {
if (this.wire.headerNumber() == Long.MIN_VALUE) {
try {
long headerNumber0 = queue.rollCycle().toIndex(cycle, store
.sequenceForPosition(StoreAppender.this, position, false));
assert (((AbstractWire) this.wire).isInsideHeader());
return isMetaData() ? headerNumber0 : headerNumber0 + 1;
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
return isMetaData() ? Long.MIN_VALUE : this.wire.headerNumber() + 1;
}
@Override
public boolean isNotComplete() {
throw new UnsupportedOperationException();
}
}
/**
* Strategise previous behaviour
*/
private class HeaderWriteStrategyOriginal implements HeaderWriteStrategy {
@Override
public boolean onContextOpen(boolean metaData, int safeLength) {
for (int i = 0; i < REPEAT_WHILE_ROLLING; i++) {
try {
assert wire != null;
long pos = store.writeHeader(wire, safeLength, timeoutMS());
position(pos);
context.isClosed = false;
context.rollbackOnClose = false;
context.wire = wire; // Jvm.isDebug() ? acquireBufferWire() : wire;
context.padToCacheAlign = padToCacheAlignMode() != Padding.NEVER;
context.metaData(metaData);
return true;
} catch (EOFException theySeeMeRolling) {
cycle = handleRoll(cycle);
}
}
throw new IllegalStateException("Unable to roll to the current cycle");
}
@Override
public void onContextClose() {
// do nothing
}
}
/**
* Buffered writes while awaiting for other appenders to release the header #403
*/
private class HeaderWriteStrategyDefer implements HeaderWriteStrategy {
@Override
public boolean onContextOpen(boolean metaData, int safeLength) {
assert wire != null;
long pos = store.tryWriteHeader(wire, safeLength);
if (pos != WireOut.TRY_WRITE_HEADER_FAILED) {
position(pos);
context.wire = wire;
context.deferredHeader = false;
} else {
context.wire = acquireBufferWire();
context.deferredHeader = true;
}
context.isClosed = false;
context.rollbackOnClose = false;
context.padToCacheAlign = padToCacheAlignMode() != Padding.NEVER;
context.metaData(metaData);
return true;
}
public void onContextClose() {
if (context.deferredHeader) {
int safeLength = (int) queue.overlapSize();
assert wire != null;
assert wire != context.wire;
for (int i = 0; i < REPEAT_WHILE_ROLLING; i++) {
try {
// TODO: we should be able to write and update the header in one go
long pos = store.writeHeader(wire, safeLength, timeoutMS());
position(pos);
long length = context.wire.bytes().copyTo(wire.bytes());
wire.bytes().writePosition(length + wire.bytes().writePosition());
context.wire = wire;
return;
} catch (EOFException theySeeMeRolling) {
cycle = handleRoll(cycle);
}
}
throw new IllegalStateException("Unable to roll to the current cycle");
}
}
}
}
// *************************************************************************
//
// TAILERS
//
// *************************************************************************
private static final class ClosableResources {
private final SingleChronicleQueue queue;
private volatile Bytes wireReference = null;
private volatile Bytes bufferWireReference = null;
private volatile Bytes wireForIndexReference = null;
private volatile CommonStore storeReference = null;
ClosableResources(final SingleChronicleQueue queue) {
this.queue = queue;
}
private static void releaseIfNotNull(final Bytes bytesReference) {
// Object is no longer reachable, check that it has not already been released
if (bytesReference != null && bytesReference.refCount() > 0) {
bytesReference.release();
}
}
private void releaseResources() {
releaseIfNotNull(wireForIndexReference);
releaseIfNotNull(wireReference);
releaseIfNotNull(bufferWireReference);
// Object is no longer reachable, check that it has not already been released
if (storeReference != null && storeReference.refCount() > 0) {
queue.release(storeReference);
}
}
}
/**
* Tailer
*/
public static class StoreTailer implements ExcerptTailer, SourceContext, ExcerptContext {
static final int INDEXING_LINEAR_SCAN_THRESHOLD = 70;
@NotNull
private final SingleChronicleQueue queue;
private final StoreTailerContext context = new StoreTailerContext();
private final ClosableResources closableResources;
private final MoveToState moveToState = new MoveToState();
long index; // index of the next read.
@Nullable
WireStore store;
private int cycle;
private long timeForNextCycle = Long.MAX_VALUE;
private TailerDirection direction = TailerDirection.FORWARD;
private Wire wireForIndex;
private boolean readAfterReplicaAcknowledged;
@NotNull
private TailerState state = UNINITIALISED;
private long indexAtCreation = Long.MIN_VALUE;
private boolean readingDocumentFound = false;
private boolean shouldUpdateIndex = false;
public StoreTailer(@NotNull final SingleChronicleQueue queue) {
this.queue = queue;
this.setCycle(Integer.MIN_VALUE);
this.index = 0;
queue.addCloseListener(this, StoreTailer::close);
closableResources = new ClosableResources(queue);
queue.ensureThatRollCycleDoesNotConflictWithExistingQueueFiles();
}
private static boolean isReadOnly(Bytes bytes) {
return bytes instanceof MappedBytes &&
((MappedBytes) bytes).isBackingFileReadOnly();
}
@Nullable
public static MessageHistory readHistory(final DocumentContext dc, MessageHistory history) {
final Wire wire = dc.wire();
if (wire == null)
return null;
Object parent = wire.parent();
wire.parent(null);
try {
final Bytes<?> bytes = wire.bytes();
final byte code = bytes.readByte(bytes.readPosition());
history.reset();
return code == (byte) FIELD_NUMBER ?
readHistoryFromBytes(wire, history) :
readHistoryFromWire(wire, history);
} finally {
wire.parent(parent);
}
}
private static MessageHistory readHistoryFromBytes(final Wire wire, MessageHistory history) {
final Bytes<?> bytes = wire.bytes();
if (MESSAGE_HISTORY_METHOD_ID != wire.readEventNumber())
return null;
((BytesMarshallable) history).readMarshallable(bytes);
return history;
}
private static MessageHistory readHistoryFromWire(final Wire wire, MessageHistory history) {
final StringBuilder sb = SBP.acquireStringBuilder();
ValueIn valueIn = wire.read(sb);
if (!MethodReader.HISTORY.contentEquals(sb))
return null;
valueIn.object(history, MessageHistory.class);
return history;
}
@Override
public boolean readDocument(@NotNull ReadMarshallable reader) {
try (@NotNull DocumentContext dc = readingDocument(false)) {
if (!dc.isPresent())
return false;
reader.readMarshallable(dc.wire());
}
return true;
}
@Override
@NotNull
public DocumentContext readingDocument() {
// trying to create an initial document without a direction should not consume a message
if (direction == NONE && (index == indexAtCreation || index == 0) && !readingDocumentFound) {
return NoDocumentContext.INSTANCE;
}
return readingDocument(false);
}
private void close() {
final Wire wire = context.wire();
if (wire != null) {
wire.bytes().release();
}
context.wire(null);
Wire w0 = wireForIndex;
if (w0 != null)
w0.bytes().release();
wireForIndex = null;
if (store != null) {
queue.release(store);
}
store = null;
}
@Override
public Wire wire() {
return context.wire();
}
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@NotNull
@Override
public String toString() {
return "StoreTailer{" +
"index sequence=" + queue.rollCycle().toSequenceNumber(index) +
", index cycle=" + queue.rollCycle().toCycle(index) +
", store=" + store + ", queue=" + queue + '}';
}
@NotNull
@Override
public DocumentContext readingDocument(boolean includeMetaData) {
if (queue.isClosed.get())
throw new IllegalStateException("Queue is closed");
try {
boolean next = false, tryAgain = true;
if (state == FOUND_CYCLE) {
try {
next = inACycle(includeMetaData, true);
tryAgain = false;
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
}
if (tryAgain)
next = next0(includeMetaData);
if (context.present(next)) {
context.setStart(context.wire().bytes().readPosition() - 4);
readingDocumentFound = true;
return context;
}
RollCycle rollCycle = queue.rollCycle();
if (state == CYCLE_NOT_FOUND && direction == FORWARD) {
int firstCycle = queue.firstCycle();
if (rollCycle.toCycle(index) < firstCycle)
toStart();
} else if (!next && state == CYCLE_NOT_FOUND && cycle != queue.cycle()) {
// appenders have moved on, it's possible that linearScan is hitting EOF, which is ignored
// since we can't find an entry at current index, indicate that we're at the end of a cycle
state = TailerState.END_OF_CYCLE;
}
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} catch (UnrecoverableTimeoutException notComplete) {
// so treat as empty.
} catch (DecoratedBufferUnderflowException e) {
// read-only tailer view is fixed, a writer could continue past the end of the view
// at the point this tailer was created. Log a warning and return no document.
if (queue.isReadOnly()) {
Jvm.warn().on(StoreTailer.class, "Tried to read past the end of a read-only view. " +
"Underlying data store may have grown since this tailer was created.", e);
} else {
throw e;
}
}
return NoDocumentContext.INSTANCE;
}
private boolean next0(boolean includeMetaData) throws UnrecoverableTimeoutException, StreamCorruptedException {
for (int i = 0; i < 1000; i++) {
switch (state) {
case UNINITIALISED:
final long firstIndex = queue.firstIndex();
if (firstIndex == Long.MAX_VALUE)
return false;
if (!moveToIndexInternal(firstIndex))
return false;
break;
case FOUND_CYCLE: {
try {
return inACycle(includeMetaData, true);
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
break;
}
case END_OF_CYCLE:
if (endOfCycle())
continue;
return false;
case BEYOND_START_OF_CYCLE:
if (beyondStartOfCycle())
continue;
return false;
case CYCLE_NOT_FOUND:
if (nextCycleNotFound())
continue;
return false;
default:
throw new AssertionError("state=" + state);
}
}
throw new IllegalStateException("Unable to progress to the next cycle, state=" + state);
}
private boolean endOfCycle() {
long oldIndex = this.index;
int currentCycle = queue.rollCycle().toCycle(oldIndex);
long nextIndex = nextIndexWithNextAvailableCycle(currentCycle);
if (nextIndex != Long.MIN_VALUE) {
if (nextEndOfCycle(nextIndex))
return true;
} else {
state = END_OF_CYCLE;
}
return false;
}
private boolean beyondStartOfCycle() throws StreamCorruptedException {
if (direction == FORWARD) {
state = UNINITIALISED;
return true;
} else if (direction == BACKWARD) {
return beyondStartOfCycleBackward();
}
throw new AssertionError("direction not set, direction=" + direction);
}
private boolean nextEndOfCycle(long nextIndex) {
if (moveToIndexInternal(nextIndex)) {
state = FOUND_CYCLE;
return true;
}
if (state == END_OF_CYCLE)
return true;
if (cycle < queue.lastCycle()) {
// we have encountered an empty file without an EOF marker
// TODO: more work needed - I thought that the appender and/or tailer would write an EOF into this file
state = END_OF_CYCLE;
return true;
}
// We are here because we are waiting for an entry to be written to this file.
// Winding back to the previous cycle results in a re-initialisation of all the objects => garbage
int nextCycle = queue.rollCycle().toCycle(nextIndex);
cycle(nextCycle, false);
state = CYCLE_NOT_FOUND;
return false;
}
private boolean beyondStartOfCycleBackward() throws StreamCorruptedException {
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
boolean foundCycle = cycle(queue.rollCycle().toCycle(index), false);
if (foundCycle) {
long lastSequenceNumberInThisCycle = store().sequenceForPosition(this, Long.MAX_VALUE, false);
long nextIndex = queue.rollCycle().toIndex(this.cycle,
lastSequenceNumberInThisCycle);
moveToIndexInternal(nextIndex);
state = FOUND_CYCLE;
return true;
}
int cycle = queue.rollCycle().toCycle(index);
long nextIndex = nextIndexWithNextAvailableCycle(cycle);
if (nextIndex != Long.MIN_VALUE) {
moveToIndexInternal(nextIndex);
state = FOUND_CYCLE;
return true;
}
state = BEYOND_START_OF_CYCLE;
return false;
}
private boolean nextCycleNotFound() {
if (index == Long.MIN_VALUE) {
if (this.store != null)
queue.release(this.store);
this.store = null;
closableResources.storeReference = null;
return false;
}
if (moveToIndexInternal(index)) {
state = FOUND_CYCLE;
return true;
}
return false;
}
private boolean inACycle(boolean includeMetaData, boolean first)
throws EOFException, StreamCorruptedException {
Wire wire = wire();
Bytes<?> bytes = wire.bytes();
bytes.readLimit(bytes.capacity());
if (readAfterReplicaAcknowledged && inACycleCheckRep()) return false;
if (direction != TailerDirection.FORWARD && inACycleNotForward()) return false;
switch (wire.readDataHeader(includeMetaData)) {
case NONE:
return inACycleNone(includeMetaData, first, bytes);
case META_DATA:
context.metaData(true);
break;
case DATA:
context.metaData(false);
break;
}
inACycleFound(bytes);
return true;
}
private boolean inACycleCheckRep() {
long lastSequenceAck = store().lastAcknowledgedIndexReplicated();
long seq = queue.rollCycle().toSequenceNumber(index);
return seq > lastSequenceAck;
}
private boolean inACycleNotForward() {
if (!moveToIndexInternal(index)) {
try {
// after toEnd() call, index is past the end of the queue
// so try to go back one (to the last record in the queue)
if (!moveToIndexInternal(index - 1)) {
return true;
}
} catch (RuntimeException e) {
// can happen if index goes negative
return true;
}
}
return false;
}
private void inACycleFound(Bytes<?> bytes) throws StreamCorruptedException {
indexEntry(bytes);
context.closeReadLimit(bytes.capacity());
wire().readAndSetLength(bytes.readPosition());
long end = bytes.readLimit();
context.closeReadPosition(end);
}
private boolean inACycleNone(boolean includeMetaData, boolean first, Bytes<?> bytes) throws EOFException, StreamCorruptedException {
// if current time is not the current cycle, then write an EOF marker and
// re-read from here, you may find that in the mean time an appender writes
// another message, however the EOF marker will always be at the end.
long now = queue.time().currentTimeMillis();
boolean cycleChange2 = now >= timeForNextCycle;
return first
&& cycleChange2
&& !isReadOnly(bytes)
&& checkMoveToNextCycle(includeMetaData, bytes);
}
private void indexEntry(@NotNull Bytes<?> bytes) throws StreamCorruptedException {
if (store().indexable(index)
&& shouldUpdateIndex
&& direction == TailerDirection.FORWARD
&& !context.isMetaData())
store.setPositionForSequenceNumber(this,
queue.rollCycle().toSequenceNumber(index), bytes
.readPosition());
}
private boolean checkMoveToNextCycle(boolean includeMetaData, @NotNull Bytes<?> bytes)
throws EOFException, StreamCorruptedException {
if (bytes.readWrite()) {
long pos = bytes.readPosition();
long lim = bytes.readLimit();
long wlim = bytes.writeLimit();
try {
bytes.writePosition(pos);
store.writeEOF(wire(), timeoutMS());
} finally {
bytes.writeLimit(wlim);
bytes.readLimit(lim);
bytes.readPosition(pos);
}
} else {
Jvm.debug().on(getClass(), "Unable to append EOF to ReadOnly store, skipping");
// even though we couldn't write EOF, we still need to indicate we're at EOF to prevent looping forever
// only do that if we waited long enough to prevent terminating too early
long now = queue.time().currentTimeMillis();
if (now >= timeForNextCycle + timeoutMS() * 2)
throw new EOFException();
}
return inACycle(includeMetaData, false);
}
private long nextIndexWithNextAvailableCycle(int cycle) {
if (cycle == Integer.MIN_VALUE)
throw new AssertionError("cycle == Integer.MIN_VALUE");
long nextIndex, doubleCheck;
// DON'T REMOVE THIS DOUBLE CHECK - ESPECIALLY WHEN USING SECONDLY THE
// FIRST RESULT CAN DIFFER FROM THE DOUBLE CHECK, AS THE APPENDER CAN RACE WITH THE
// TAILER
do {
nextIndex = nextIndexWithNextAvailableCycle0(cycle);
if (nextIndex != Long.MIN_VALUE) {
int nextCycle = queue.rollCycle().toCycle(nextIndex);
if (nextCycle == cycle + 1) {
// don't do the double check if the next cycle is adjacent to the current
return nextIndex;
}
}
doubleCheck = nextIndexWithNextAvailableCycle0(cycle);
} while (nextIndex != doubleCheck);
if (nextIndex != Long.MIN_VALUE && queue.rollCycle().toCycle(nextIndex) - 1 != cycle) {
/*
* lets say that you were using a roll cycle of TEST_SECONDLY
* and you wrote a message to the queue, if you created a tailer and read the first message,
* then waited around 22 seconds before writing the next message, when the tailer
* came to read the next message, there would be a gap of 22 cycle files
* that did not exist, that is what this is reporting. If you are using daily rolling,
* and writing every day, you should not see this message.
*/
LOG.debug("Rolled " + (queue
.rollCycle().toCycle(nextIndex) - cycle) + " " + "times to find the " +
"next cycle file. This can occur if your appenders have not written " +
"anything for a while, leaving the cycle files with a gap.");
}
return nextIndex;
}
private long nextIndexWithNextAvailableCycle0(int cycle) {
if (cycle > queue.lastCycle() || direction == TailerDirection.NONE) {
return Long.MIN_VALUE;
}
int nextCycle = cycle + direction.add();
boolean found = cycle(nextCycle, false);
if (found)
return nextIndexWithinFoundCycle(nextCycle);
try {
int nextCycle0 = queue.nextCycle(this.cycle, direction);
if (nextCycle0 == -1)
return Long.MIN_VALUE;
return nextIndexWithinFoundCycle(nextCycle0);
} catch (ParseException e) {
throw new IllegalStateException(e);
}
}
private long nextIndexWithinFoundCycle(int nextCycle) {
state = FOUND_CYCLE;
if (direction == FORWARD)
return queue.rollCycle().toIndex(nextCycle, 0);
if (direction == BACKWARD) {
try {
long lastSequenceNumber0 = store().lastSequenceNumber(this);
return queue.rollCycle().toIndex(nextCycle, lastSequenceNumber0);
} catch (Exception e) {
throw new AssertionError(e);
}
} else {
throw new IllegalStateException("direction=" + direction);
}
}
/**
* @return provides an index that includes the cycle number
*/
@Override
public long index() {
return this.index;
}
@Override
public int cycle() {
return this.cycle;
}
@Override
public boolean moveToIndex(final long index) {
if (moveToState.canReuseLastIndexMove(index, state, direction, queue, wire())) {
return true;
} else if (moveToState.indexIsCloseToAndAheadOfLastIndexMove(index, state, direction, queue)) {
final long knownIndex = moveToState.lastMovedToIndex;
final boolean found =
this.store.linearScanTo(index, knownIndex, this,
moveToState.readPositionAtLastMove) == ScanResult.FOUND;
if (found) {
index(index);
moveToState.onSuccessfulScan(index, direction, wire().bytes().readPosition());
}
return found;
}
return moveToIndexInternal(index);
}
ScanResult moveToIndexResult(long index) {
final int cycle = queue.rollCycle().toCycle(index);
final long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
if (LOG.isTraceEnabled()) {
Jvm.debug().on(getClass(), "moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (cycle != this.cycle || state != FOUND_CYCLE) {
// moves to the expected cycle
if (!cycle(cycle, false))
return ScanResult.NOT_REACHED;
}
index(index);
ScanResult scanResult = this.store().moveToIndexForRead(this, sequenceNumber);
Bytes<?> bytes = wire().bytes();
if (scanResult == FOUND) {
state = FOUND_CYCLE;
moveToState.onSuccessfulLookup(index, direction, bytes.readPosition());
return scanResult;
} else if (scanResult == END_OF_FILE) {
state = END_OF_CYCLE;
return scanResult;
} else if (scanResult == NOT_FOUND && this.cycle < this.queue.lastCycle) {
state = END_OF_CYCLE;
return END_OF_FILE;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@NotNull
@Override
public final ExcerptTailer toStart() {
assert direction != BACKWARD;
final int firstCycle = queue.firstCycle();
if (firstCycle == Integer.MAX_VALUE) {
state = UNINITIALISED;
return this;
}
if (firstCycle != this.cycle) {
// moves to the expected cycle
boolean found = cycle(firstCycle, false);
assert found || store == null;
if (found)
state = FOUND_CYCLE;
}
index(queue.rollCycle().toIndex(cycle, 0));
state = FOUND_CYCLE;
if (wire() != null)
wire().bytes().readPosition(0);
return this;
}
private boolean moveToIndexInternal(final long index) {
moveToState.indexMoveCount++;
final ScanResult scanResult = moveToIndexResult(index);
return scanResult == FOUND;
}
/**
* gives approximately the last index, can not be relied on as the last index may have
* changed just after this was called. For this reason, this code is not in queue as it
* should only be an internal method
*
* @return the last index at the time this method was called, or Long.MIN_VALUE if none.
*/
private long approximateLastIndex() {
RollCycle rollCycle = queue.rollCycle();
final int lastCycle = queue.lastCycle();
try {
if (lastCycle == Integer.MIN_VALUE)
return Long.MIN_VALUE;
final WireStore wireStore = queue.storeForCycle(lastCycle, queue.epoch(), false);
this.setCycle(lastCycle);
if (wireStore == null)
throw new IllegalStateException("Store not found for cycle " + Long.toHexString(lastCycle) + ". Probably the files were removed?");
if (store != null)
queue.release(store);
if (this.store != wireStore) {
this.store = wireStore;
closableResources.storeReference = wireStore;
resetWires();
}
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
long sequenceNumber = store.lastSequenceNumber(this);
// fixes #378
if (sequenceNumber == -1L) {
// nothing has been written yet, so point to start of cycle
return rollCycle.toIndex(lastCycle, 0L);
}
return rollCycle.toIndex(lastCycle, sequenceNumber);
} catch (@NotNull StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
}
}
private boolean headerNumberCheck(@NotNull AbstractWire wire) {
wire.headNumberCheck((actual, position) -> {
try {
long expecting = store.sequenceForPosition(this, position, false);
if (actual == expecting)
return true;
LOG.error("", new AssertionError("header number check failed " +
"expecting=" + expecting +
" != actual=" + actual));
return false;
} catch (Exception e) {
LOG.error("", e);
return false;
}
});
return true;
}
private void resetWires() {
WireType wireType = queue.wireType();
final AbstractWire wire = (AbstractWire) readAnywhere(wireType.apply(store().bytes()));
assert headerNumberCheck(wire);
this.context.wire(wire);
wire.parent(this);
Wire wireForIndexOld = wireForIndex;
wireForIndex = readAnywhere(wireType.apply(store().bytes()));
closableResources.wireForIndexReference = wireForIndex.bytes();
closableResources.wireReference = wire.bytes();
assert headerNumberCheck((AbstractWire) wireForIndex);
if (wireForIndexOld != null) {
releaseWireResources(wireForIndexOld);
}
}
@NotNull
private Wire readAnywhere(@NotNull Wire wire) {
Bytes<?> bytes = wire.bytes();
bytes.readLimit(bytes.capacity());
return wire;
}
@NotNull
@Override
public ExcerptTailer toEnd() {
long index = approximateLastIndex();
if (index == Long.MIN_VALUE) {
if (state() == TailerState.CYCLE_NOT_FOUND)
state = UNINITIALISED;
return this;
}
final ScanResult scanResult = moveToIndexResult(index);
switch (scanResult) {
case NOT_FOUND:
if (moveToIndexResult(index - 1) == FOUND)
state = FOUND_CYCLE;
break;
case FOUND:
if (direction == FORWARD) {
final ScanResult result = moveToIndexResult(++index);
switch (result) {
case FOUND:
// the end moved!!
state = FOUND_CYCLE;
break;
case NOT_REACHED:
throw new IllegalStateException("NOT_REACHED after FOUND");
case NOT_FOUND:
state = FOUND_CYCLE;
break;
case END_OF_FILE:
state = END_OF_CYCLE;
break;
default:
throw new IllegalStateException("Unknown ScanResult: " + result);
}
}
break;
case NOT_REACHED:
approximateLastIndex();
throw new IllegalStateException("NOT_REACHED index: " + Long.toHexString(index));
case END_OF_FILE:
state = END_OF_CYCLE;
break;
default:
throw new IllegalStateException("Unknown ScanResult: " + scanResult);
}
return this;
}
@Override
public TailerDirection direction() {
return direction;
}
@NotNull
@Override
public ExcerptTailer direction(TailerDirection direction) {
final TailerDirection oldDirection = this.direction();
this.direction = direction;
if (oldDirection == TailerDirection.BACKWARD &&
direction == TailerDirection.FORWARD) {
moveToIndexInternal(index);
}
return this;
}
@Override
@NotNull
public RollingChronicleQueue queue() {
return queue;
}
@Override
public Runnable getCloserJob() {
return closableResources::releaseResources;
}
/**
* Can be used to manually release resources when this
* StoreTailer is no longer used.
*/
public void releaseResources() {
queue.removeCloseListener(this);
getCloserJob().run();
}
private void incrementIndex() {
RollCycle rollCycle = queue.rollCycle();
long seq = rollCycle.toSequenceNumber(this.index);
int cycle = rollCycle.toCycle(this.index);
seq += direction.add();
switch (direction) {
case NONE:
break;
case FORWARD:
// if it runs out of seq number it will flow over to tomorrows cycle file
if (rollCycle.toSequenceNumber(seq) < seq) {
cycle(cycle + 1, false);
LOG.warn("we have run out of sequence numbers, so will start to write to " +
"the next .cq4 file, the new cycle=" + cycle);
seq = 0;
}
break;
case BACKWARD:
if (seq < 0) {
windBackCycle(cycle);
return;
}
break;
}
this.index = rollCycle.toIndex(cycle, seq);
}
private void windBackCycle(int cycle) {
if (tryWindBack(cycle - 1))
return;
cycle--;
for (long first = queue.firstCycle(); cycle >= first; cycle--) {
if (tryWindBack(cycle))
return;
}
this.index(queue.rollCycle().toIndex(cycle, -1));
this.state = BEYOND_START_OF_CYCLE;
}
private boolean tryWindBack(int cycle) {
long count = queue.exceptsPerCycle(cycle);
if (count <= 0)
return false;
RollCycle rollCycle = queue.rollCycle();
moveToIndexInternal(rollCycle.toIndex(cycle, count - 1));
this.state = FOUND_CYCLE;
return true;
}
// DON'T INLINE THIS METHOD, as it's used by enterprise chronicle queue
void index(long index) {
this.index = index;
if (indexAtCreation == Long.MIN_VALUE) {
indexAtCreation = index;
}
moveToState.reset();
}
private boolean cycle(final int cycle, boolean createIfAbsent) {
if (this.cycle == cycle && state == FOUND_CYCLE)
return true;
WireStore nextStore = this.queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
if (nextStore == null && this.store == null)
return false;
if (nextStore == null) {
if (direction == BACKWARD)
state = BEYOND_START_OF_CYCLE;
else
state = CYCLE_NOT_FOUND;
return false;
}
if (store != null)
queue.release(store);
if (nextStore == this.store)
return true;
context.wire(null);
this.store = nextStore;
closableResources.storeReference = nextStore;
this.state = FOUND_CYCLE;
this.setCycle(cycle);
resetWires();
final Wire wire = wire();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
return true;
}
void release() {
if (store != null) {
queue.release(store);
store = null;
closableResources.storeReference = null;
}
state = UNINITIALISED;
}
@Override
public void readAfterReplicaAcknowledged(boolean readAfterReplicaAcknowledged) {
this.readAfterReplicaAcknowledged = readAfterReplicaAcknowledged;
}
@Override
public boolean readAfterReplicaAcknowledged() {
return readAfterReplicaAcknowledged;
}
@NotNull
@Override
public TailerState state() {
return state;
}
@NotNull
@Override
public ExcerptTailer afterLastWritten(@NotNull ChronicleQueue queue) {
if (queue == this.queue)
throw new IllegalArgumentException("You must pass the queue written to, not the queue read");
@NotNull ExcerptTailer tailer = queue.createTailer()
.direction(BACKWARD)
.toEnd();
@NotNull VanillaMessageHistory messageHistory = new VanillaMessageHistory();
while (true) {
try (DocumentContext context = tailer.readingDocument()) {
if (!context.isData()) {
toStart();
return this;
}
MessageHistory veh = readHistory(context, messageHistory);
if (veh == null)
continue;
int i = veh.sources() - 1;
if (i < 0)
continue;
if (veh.sourceId(i) != this.sourceId())
continue;
long sourceIndex = veh.sourceIndex(i);
if (!moveToIndexInternal(sourceIndex)) {
final String errorMessage = String.format(
"Unable to move to sourceIndex %s in queue %s",
Long.toHexString(sourceIndex), this.queue.fileAbsolutePath());
throw new IORuntimeException(errorMessage + extraInfo(tailer, messageHistory));
}
try (DocumentContext content = readingDocument()) {
if (!content.isPresent()) {
final String errorMessage = String.format(
"No readable document found at sourceIndex %s in queue %s",
Long.toHexString(sourceIndex + 1), this.queue.fileAbsolutePath());
throw new IORuntimeException(errorMessage + extraInfo(tailer, messageHistory));
}
// skip this message and go to the next.
}
return this;
}
}
}
private String extraInfo(@NotNull ExcerptTailer tailer, @NotNull VanillaMessageHistory messageHistory) {
return String.format(
". That sourceIndex was determined fom the last entry written to queue %s " +
"(message index %s, message history %s). If source queue is replicated then " +
"sourceIndex may not have been replicated yet",
tailer.queue().fileAbsolutePath(), Long.toHexString(tailer.index()), WireType.TEXT.asString(messageHistory));
}
@NotNull
@Override
public ExcerptTailer indexing(final boolean indexing) {
this.shouldUpdateIndex = indexing;
return this;
}
public void lastAcknowledgedIndexReplicated(long acknowledgeIndex) {
if (Jvm.isDebugEnabled(getClass()))
Jvm.debug().on(getClass(), "received lastAcknowledgedIndexReplicated=" + Long.toHexString(acknowledgeIndex) + " ,file=" + queue().fileAbsolutePath());
RollCycle rollCycle = queue.rollCycle();
int cycle0 = rollCycle.toCycle(acknowledgeIndex);
// cycle is the same so the same tailer can be used.
if (cycle0 == cycle()) {
store.lastAcknowledgedIndexReplicated(acknowledgeIndex);
return;
}
// the reason that we use the temp tailer is to prevent this tailer from having its cycle changed
// NOTE: This is a very expensive operation.
StoreTailer temp = queue.acquireTailer();
try {
if (!temp.cycle(cycle0, false)) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(acknowledgeIndex) + " for a cycle which could not found");
return;
}
WireStore store = temp.store;
if (store == null) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(acknowledgeIndex) + " discarded.");
return;
}
store.lastAcknowledgedIndexReplicated(acknowledgeIndex);
} finally {
temp.release();
}
}
public void lastIndexReplicated(long lastIndexReplicated) {
if (Jvm.isDebugEnabled(getClass()))
Jvm.debug().on(getClass(), "received lastIndexReplicated=" + Long.toHexString(lastIndexReplicated) + " ,file=" + queue().fileAbsolutePath());
RollCycle rollCycle = queue.rollCycle();
int cycle0 = rollCycle.toCycle(lastIndexReplicated);
// cycle is the same so the same tailer can be used.
if (cycle0 == cycle()) {
store().lastIndexReplicated(lastIndexReplicated);
return;
}
// the reason that we use the temp tailer is to prevent this tailer from having its cycle changed
// NOTE: This is a very expensive operation.
StoreTailer temp = queue.acquireTailer();
try {
if (!temp.cycle(cycle0, false)) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(lastIndexReplicated) + " for a cycle which could not found");
return;
}
if (temp.store == null) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(lastIndexReplicated) + " discarded.");
return;
}
temp.store().lastIndexReplicated(lastIndexReplicated);
} finally {
temp.release();
}
}
public long lastAcknowledgedIndexReplicated() {
return ((StoreAppender) queue.acquireAppender()).store().lastAcknowledgedIndexReplicated();
}
public long lastIndexReplicated() {
return ((StoreAppender) queue.acquireAppender()).store().lastIndexReplicated();
}
public void setCycle(int cycle) {
this.cycle = cycle;
timeForNextCycle = cycle == Integer.MIN_VALUE ? Long.MAX_VALUE :
(long) (cycle + 1) * queue.rollCycle().length() + queue.epoch();
}
// visible for testing
int getIndexMoveCount() {
return moveToState.indexMoveCount;
}
@NotNull
public WireStore store() {
if (store == null)
setCycle(cycle());
return store;
}
private static final class MoveToState {
private long lastMovedToIndex = Long.MIN_VALUE;
private TailerDirection directionAtLastMoveTo = TailerDirection.NONE;
private long readPositionAtLastMove = Long.MIN_VALUE;
private int indexMoveCount = 0;
void onSuccessfulLookup(
final long movedToIndex, final TailerDirection direction,
final long readPosition) {
this.lastMovedToIndex = movedToIndex;
this.directionAtLastMoveTo = direction;
this.readPositionAtLastMove = readPosition;
}
void onSuccessfulScan(
final long movedToIndex, final TailerDirection direction,
final long readPosition) {
this.lastMovedToIndex = movedToIndex;
this.directionAtLastMoveTo = direction;
this.readPositionAtLastMove = readPosition;
}
void reset() {
lastMovedToIndex = Long.MIN_VALUE;
directionAtLastMoveTo = TailerDirection.NONE;
readPositionAtLastMove = Long.MIN_VALUE;
}
private boolean indexIsCloseToAndAheadOfLastIndexMove(
final long index, final TailerState state, final TailerDirection direction,
final SingleChronicleQueue queue) {
return lastMovedToIndex != Long.MIN_VALUE &&
index - lastMovedToIndex < INDEXING_LINEAR_SCAN_THRESHOLD &&
state == FOUND_CYCLE &&
direction == directionAtLastMoveTo &&
queue.rollCycle().toCycle(index) == queue.rollCycle().toCycle(lastMovedToIndex) &&
index > lastMovedToIndex;
}
private boolean canReuseLastIndexMove(
final long index, final TailerState state, final TailerDirection direction,
final SingleChronicleQueue queue, final Wire wire) {
return ((wire == null) || wire.bytes().readPosition() == readPositionAtLastMove) &&
index == this.lastMovedToIndex && index != 0 && state == FOUND_CYCLE &&
direction == directionAtLastMoveTo &&
queue.rollCycle().toCycle(index) == queue.rollCycle().toCycle(lastMovedToIndex);
}
}
class StoreTailerContext extends BinaryReadDocumentContext {
boolean rollbackOnClose = false;
StoreTailerContext() {
super(null);
}
@Override
public void rollbackOnClose() {
rollbackOnClose = true;
}
@Override
public long index() {
return StoreTailer.this.index();
}
@Override
public int sourceId() {
return StoreTailer.this.sourceId();
}
@Override
public void close() {
try {
if (rollbackOnClose) {
present = false;
if (start != -1)
wire.bytes().readPosition(start).readLimit(readLimit);
start = -1;
return;
}
if (isPresent() && !isMetaData())
incrementIndex();
super.close();
// assert wire == null || wire.endUse();
} finally {
rollbackOnClose = false;
}
}
boolean present(boolean present) {
return this.present = present;
}
public void wire(@Nullable AbstractWire wire) {
AbstractWire oldWire = this.wire;
this.wire = wire;
if (oldWire != null) {
releaseWireResources(oldWire);
}
}
}
}
} | src/main/java/net/openhft/chronicle/queue/impl/single/SingleChronicleQueueExcerpts.java | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.*;
import net.openhft.chronicle.bytes.util.DecoratedBufferUnderflowException;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.pool.StringBuilderPool;
import net.openhft.chronicle.core.time.TimeProvider;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.*;
import net.openhft.chronicle.wire.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.nio.BufferOverflowException;
import java.text.ParseException;
import static net.openhft.chronicle.queue.TailerDirection.*;
import static net.openhft.chronicle.queue.TailerState.*;
import static net.openhft.chronicle.queue.impl.single.ScanResult.*;
import static net.openhft.chronicle.wire.BinaryWireCode.FIELD_NUMBER;
public class SingleChronicleQueueExcerpts {
private static final Logger LOG = LoggerFactory.getLogger(SingleChronicleQueueExcerpts.class);
private static final int MESSAGE_HISTORY_METHOD_ID = -1;
private static StringBuilderPool SBP = new StringBuilderPool();
private static void releaseWireResources(final Wire wire) {
StoreComponentReferenceHandler.queueForRelease(wire);
}
// *************************************************************************
//
// APPENDERS
//
// *************************************************************************
@FunctionalInterface
interface WireWriter<T> {
void write(T message, WireOut wireOut);
}
public interface InternalAppender {
void writeBytes(long index, BytesStore bytes);
}
static class StoreAppender implements ExcerptAppender, ExcerptContext, InternalAppender {
private static final long PRETOUCHER_PREROLL_TIME_MS = 2_000L;
private final TimeProvider pretouchTimeProvider;
private WireStore pretouchStore;
private int pretouchCycle;
static final int REPEAT_WHILE_ROLLING = 128;
@NotNull
private final SingleChronicleQueue queue;
@NotNull
private final StoreAppenderContext context;
private final ClosableResources closableResources;
@NotNull
private final HeaderWriteStrategy headerWriteStrategy;
private final WireStorePool storePool;
@Nullable
WireStore store;
private int cycle = Integer.MIN_VALUE;
@Nullable
private Wire wire;
@Nullable
private Wire bufferWire; // if you have a buffered write.
@Nullable
private Wire wireForIndex;
private long position = 0;
@Nullable
private volatile Thread appendingThread = null;
private long lastIndex = Long.MIN_VALUE;
private boolean lazyIndexing = false;
private long lastPosition;
private int lastCycle;
@Nullable
private PretoucherState pretoucher = null;
private Padding padToCacheLines = Padding.SMART;
StoreAppender(@NotNull SingleChronicleQueue queue, boolean progressOnContention, @NotNull WireStorePool storePool) {
this.queue = queue;
queue.addCloseListener(this, StoreAppender::close);
context = new StoreAppenderContext();
this.storePool = storePool;
closableResources = new ClosableResources(queue);
queue.ensureThatRollCycleDoesNotConflictWithExistingQueueFiles();
headerWriteStrategy = progressOnContention ? new HeaderWriteStrategyDefer() : new HeaderWriteStrategyOriginal();
pretouchTimeProvider = () -> queue.time().currentTimeMillis() + PRETOUCHER_PREROLL_TIME_MS;
}
@NotNull
public WireStore store() {
if (store == null)
setCycle(cycle());
return store;
}
@Override
@NotNull
public Padding padToCacheAlignMode() {
return padToCacheLines;
}
/**
* @param padToCacheLines the default for chronicle queue is Padding.SMART, which
* automatically pads all method calls other than {@link
* StoreAppender#writeBytes(net.openhft.chronicle.bytes.WriteBytesMarshallable)}
* and {@link StoreAppender#writeText(java.lang.CharSequence)}.
* Which can not be padded with out changing the message format, The
* reason we pad is to ensure that a message header does not straggle
* a cache line.
*/
@Override
public void padToCacheAlign(Padding padToCacheLines) {
this.padToCacheLines = padToCacheLines;
}
/**
* @param marshallable to write to excerpt.
*/
@Override
public void writeBytes(@NotNull WriteBytesMarshallable marshallable) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
marshallable.writeMarshallable(dc.wire().bytes());
if (padToCacheAlignMode() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
@Override
public void writeText(@NotNull CharSequence text) throws UnrecoverableTimeoutException {
try (DocumentContext dc = writingDocument()) {
dc.wire().bytes()
.append8bit(text);
if (padToCacheAlignMode() != Padding.ALWAYS)
((StoreAppenderContext) dc).padToCacheAlign = false;
}
}
void close() {
Wire w0 = wireForIndex;
wireForIndex = null;
if (w0 != null)
w0.bytes().release();
Wire w = wire;
wire = null;
if (w != null) {
w.bytes().release();
}
releasePretouchStore();
if (store != null) {
storePool.release(store);
}
if (bufferWire != null) {
bufferWire.bytes().release();
bufferWire = null;
}
store = null;
storePool.close();
}
/**
* this is not currently thread safe so should be run on the same thread as the appender
*/
@Override
public void pretouch() {
if (queue.isClosed())
throw new RuntimeException("Queue Closed");
try {
int qCycle = queue.cycle();
setCycle(qCycle);
WireStore store = this.store;
if (store == null || store.bytes().isClosed())
return;
if (pretoucher == null)
pretoucher = new PretoucherState(store::writePosition);
Wire wire = this.wire;
if (wire != null && wire.bytes().bytesStore().refCount() > 0)
pretoucher.pretouch((MappedBytes) wire.bytes());
if (pretouchStore != null && pretouchCycle == qCycle) {
releasePretouchStore();
} else {
int pretouchCycle0 = queue.cycle(pretouchTimeProvider);
if (pretouchCycle0 != qCycle && pretouchCycle != pretouchCycle0) {
releasePretouchStore();
pretouchStore = queue.storeSupplier().acquire(pretouchCycle0, true);
pretouchCycle = pretouchCycle0;
pretoucher = null;
if (Jvm.isDebugEnabled(getClass()))
Jvm.debug().on(getClass(), "Pretoucher ROLLING to next file=" +
pretouchStore.file());
}
}
} catch (Throwable e) {
e.printStackTrace();
Jvm.warn().on(getClass(), e);
}
}
private void releasePretouchStore() {
WireStore pretouchStore = this.pretouchStore;
if (pretouchStore == null)
return;
pretouchStore.release();
pretouchCycle = -1;
this.pretouchStore = null;
}
@Nullable
@Override
public Wire wire() {
return wire;
}
@Nullable
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
void lastIndex(long index) {
this.lastIndex = index;
}
@NotNull
@Override
public ExcerptAppender lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
try {
resetPosition();
} catch (EOFException ex) {
throw new IllegalStateException("EOF found");
}
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public boolean recordHistory() {
return sourceId() != 0;
}
void setCycle(int cycle) {
if (cycle != this.cycle)
setCycle2(cycle, true);
}
private void setCycle2(int cycle, boolean createIfAbsent) {
if (cycle < 0)
throw new IllegalArgumentException("You can not have a cycle that starts " +
"before Epoch. cycle=" + cycle);
SingleChronicleQueue queue = this.queue;
if (this.store != null) {
storePool.release(this.store);
}
this.store = storePool.acquire(cycle, queue.epoch(), createIfAbsent);
closableResources.storeReference = store;
resetWires(queue);
// only set the cycle after the wire is set.
this.cycle = cycle;
assert wire.startUse();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
try {
resetPosition();
queue.onRoll(cycle);
} catch (EOFException eof) {
handleRoll(cycle);
}
}
private void resetWires(@NotNull SingleChronicleQueue queue) {
WireType wireType = queue.wireType();
{
Wire oldw = this.wire;
this.wire = wireType.apply(store.bytes());
closableResources.wireReference = this.wire.bytes();
if (oldw != null) {
releaseWireResources(oldw);
}
}
{
Wire old = this.wireForIndex;
this.wireForIndex = wireType.apply(store.bytes());
closableResources.wireForIndexReference = wireForIndex.bytes();
if (old != null) {
releaseWireResources(old);
}
}
}
private void resetPosition() throws UnrecoverableTimeoutException, EOFException {
try {
if (store == null || wire == null)
return;
position(store.writePosition());
Bytes<?> bytes = wire.bytes();
int header = bytes.readVolatileInt(position);
if (header == Wires.END_OF_DATA) {
throw new EOFException();
}
assert position == 0 || Wires.isReadyData(header);
bytes.writePosition(position + 4 + Wires.lengthOf(header));
if (lazyIndexing) {
wire.headerNumber(Long.MIN_VALUE);
return;
}
final long headerNumber = store.sequenceForPosition(this, position, true);
wire.headerNumber(queue.rollCycle().toIndex(cycle, headerNumber + 1) - 1);
assert lazyIndexing || wire.headerNumber() != -1 || checkIndex(wire.headerNumber(), position);
} catch (@NotNull BufferOverflowException | StreamCorruptedException e) {
throw new AssertionError(e);
}
assert checkWritePositionHeaderNumber();
}
@NotNull
@Override
public DocumentContext writingDocument(boolean metaData) throws UnrecoverableTimeoutException {
assert checkAppendingThread();
assert checkWritePositionHeaderNumber();
if (queue.isClosed.get())
throw new IllegalStateException("Queue is closed");
if (Thread.currentThread().isInterrupted())
throw new IllegalStateException("Queue won't write from an interrupted thread");
boolean ok = false;
try {
int cycle = queue.cycle();
if (wire == null) {
// we have check it the queue file has rolled due to an early EOF
cycle = Math.max(queue.lastCycle(), cycle);
setCycle2(cycle, true);
} else if (this.cycle != cycle)
rollCycleTo(cycle);
int safeLength = (int) queue.overlapSize();
ok = headerWriteStrategy.onContextOpen(metaData, safeLength);
return context;
} finally {
assert ok || resetAppendingThread();
}
}
private int handleRoll(int cycle) {
assert !((AbstractWire) wire).isInsideHeader();
int qCycle = queue.cycle();
if (cycle < queue.cycle()) {
setCycle2(cycle = qCycle, true);
} else if (cycle == qCycle) {
// for the rare case where the qCycle has just changed in the last
// few milliseconds since
setCycle2(++cycle, true);
} else {
throw new IllegalStateException("Found an EOF on the next cycle file," +
" this next file, should not have an EOF as its cycle " +
"number is greater than the current cycle (based on the " +
"current time), this should only happen " +
"if it was written by a different appender set with a different " +
"EPOCH or different roll cycle." +
"All your appenders ( that write to a given directory ) " +
"should have the same EPOCH and roll cycle" +
" qCycle=" + qCycle + ", cycle=" + cycle + ", queue-file=" + queue.fileAbsolutePath());
}
return cycle;
}
boolean checkWritePositionHeaderNumber() {
if (wire == null || wire.headerNumber() == Long.MIN_VALUE) return true;
try {
long pos1 = position;
/*
long posMax = store.writePosition();
if (pos1 > posMax+4) {
System.out.println(queue.dump());
String message = "########### " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" posMax: " + posMax;
System.err.println(message);
throw new AssertionError(message);
}*/
long seq1 = queue.rollCycle().toSequenceNumber(wire.headerNumber() + 1) - 1;
long seq2 = store.sequenceForPosition(this, pos1, true);
if (seq1 != seq2) {
// System.out.println(queue.dump());
String message = "~~~~~~~~~~~~~~ " +
"thread: " + Thread.currentThread().getName() +
" pos1: " + pos1 +
" seq1: " + seq1 +
" seq2: " + seq2;
System.err.println(message);
throw new AssertionError(message);
}
} catch (IOException e) {
Jvm.fatal().on(getClass(), e);
throw Jvm.rethrow(e);
}
return true;
}
@NotNull
@Override
public DocumentContext writingDocument(long index) {
context.isClosed = false;
assert checkAppendingThread();
context.wire = acquireBufferWire();
context.wire.headerNumber(index);
context.isClosed = false;
return context;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public void writeBytes(@NotNull BytesStore bytes) throws UnrecoverableTimeoutException {
append((m, w) -> w.bytes().write(m), bytes);
}
@NotNull
Wire acquireBufferWire() {
if (bufferWire == null) {
bufferWire = queue.wireType().apply(Bytes.elasticByteBuffer());
closableResources.bufferWireReference = bufferWire.bytes();
} else {
bufferWire.clear();
}
return bufferWire;
}
/**
* Write bytes at an index, but only if the index is at the end of the chronicle.
* If index is after the end of the chronicle, throw an IllegalStateException. If the
* index is before the end of the chronicle then do not change the state of the chronicle.
* <p>Thread-safe</p>
*
* @param index index to write at. Only if index is at the end of the chronicle will the bytes get written
* @param bytes payload
*/
public void writeBytes(long index, @NotNull BytesStore bytes) {
if (queue.isClosed.get())
throw new IllegalStateException("Queue is closed");
int cycle = queue.rollCycle().toCycle(index);
if (wire == null)
setCycle2(cycle, true);
else if (this.cycle != cycle)
rollCycleTo(cycle);
int safeLength = (int) queue.overlapSize();
assert checkAppendingThread();
try {
long pos = wire.bytes().writePosition();
// opening the context locks the chronicle
headerWriteStrategy.onContextOpen(false, safeLength);
boolean rollbackDontClose = index != wire.headerNumber() + 1;
if (rollbackDontClose) {
wire.bytes().writeSkip(-4);
wire.bytes().writeVolatileInt(wire.bytes().writePosition(), 0);
wire.bytes().writeLimit(wire.bytes().capacity());
this.position = pos;
((AbstractWire) wire).forceNotInsideHeader();
if (index > wire.headerNumber() + 1)
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue");
// TODO: assert bytes.equalBytes(wire.bytes() ...);
Jvm.warn().on(getClass(), "Trying to overwrite index " + Long.toHexString(index) + " which is before the end of the queue");
return;
}
try {
context.wire().bytes().write(bytes);
} finally {
context.close();
}
} finally {
this.appendingThread = null;
context.isClosed = true;
}
}
private void position(long position) {
// did the position jump too far forward.
if (position > store.writePosition() + queue.blockSize())
throw new IllegalArgumentException("pos: " + position + ", store.writePosition()=" +
store.writePosition() + " queue.blockSize()=" + queue.blockSize());
// System.err.println("----- "+Thread.currentThread().getName()+" pos: "+position);
this.position = position;
}
@Override
public long lastIndexAppended() {
if (lastIndex != Long.MIN_VALUE)
return lastIndex;
if (lastPosition == Long.MIN_VALUE || wire == null) {
throw new IllegalStateException("nothing has been appended, so there is no last index");
}
try {
long sequenceNumber = store.sequenceForPosition(this, lastPosition, true);
long index = queue.rollCycle().toIndex(lastCycle, sequenceNumber);
lastIndex(index);
return index;
} catch (Exception e) {
throw Jvm.rethrow(e);
}
}
@Override
public int cycle() {
if (cycle == Integer.MIN_VALUE) {
int cycle = this.queue.lastCycle();
if (cycle < 0)
cycle = queue.cycle();
setCycle2(cycle, true);
}
return cycle;
}
@Override
@NotNull
public SingleChronicleQueue queue() {
return queue;
}
@Override
public Runnable getCloserJob() {
return closableResources::releaseResources;
}
/**
* overwritten in delta wire
*
* @param wire
* @param index
*/
void beforeAppend(Wire wire, long index) {
}
private <T> void append(@NotNull WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException {
assert checkAppendingThread();
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
try {
position(store.writeHeader(wire, (int) queue.overlapSize(), timeoutMS()));
assert ((AbstractWire) wire).isInsideHeader();
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(position, false);
lastIndex(wire.headerNumber());
lastPosition = position;
lastCycle = cycle;
store.writePosition(position);
writeIndexForPosition(lastIndex, position);
} catch (EOFException theySeeMeRolling) {
try {
append2(wireWriter, writer);
} catch (EOFException e) {
throw new AssertionError(e);
}
}
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
assert resetAppendingThread();
}
}
private void rollCycleTo(int cycle) throws UnrecoverableTimeoutException {
if (wire != null) {
// only a valid check if the wire was set.
if (this.cycle == cycle)
throw new AssertionError();
store.writeEOF(wire, timeoutMS());
}
setCycle2(cycle, true);
}
/**
* Write an EOF marker on the current cycle if it is about to roll. It would do this any way
* if a new message was written, but this doesn't create a new cycle or add a message.
*/
public void writeEndOfCycleIfRequired() {
if (wire != null && queue.cycle() != cycle) {
store.writeEOF(wire, timeoutMS());
}
}
<T> void append2(@NotNull WireWriter<T> wireWriter, T writer) throws
UnrecoverableTimeoutException, EOFException, StreamCorruptedException {
setCycle(Math.max(queue.cycle(), cycle + 1));
position(store.writeHeader(wire, (int) queue.overlapSize(), timeoutMS()));
beforeAppend(wire, wire.headerNumber() + 1);
wireWriter.write(writer, wire);
wire.updateHeader(position, false);
}
private boolean checkAppendingThread() {
Thread appendingThread = this.appendingThread;
Thread currentThread = Thread.currentThread();
if (appendingThread != null) {
if (appendingThread == currentThread)
throw new IllegalStateException("Nested blocks of writingDocument() not supported");
throw new IllegalStateException("Attempting to use Appender in " + currentThread + " while used by " + appendingThread);
}
this.appendingThread = currentThread;
return true;
}
private boolean resetAppendingThread() {
if (this.appendingThread == null)
throw new IllegalStateException("Attempting to release Appender in " + Thread.currentThread() + " but already released");
this.appendingThread = null;
return true;
}
void writeIndexForPosition(long index, long position)
throws UnrecoverableTimeoutException, StreamCorruptedException {
if (!lazyIndexing) {
long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
store.setPositionForSequenceNumber(this, sequenceNumber, position);
}
}
boolean checkIndex(long index, long position) {
try {
final long seq1 = queue.rollCycle().toSequenceNumber(index + 1) - 1;
final long seq2 = store.sequenceForPosition(this, position, true);
if (seq1 != seq2) {
final long seq3 = ((SingleChronicleQueueStore) store).indexing
.linearScanByPosition(wireForIndex(), position, 0, 0, true);
System.out.println("Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + Long.toHexString(seq1) +
" seq2: " + Long.toHexString(seq2) +
" seq3: " + Long.toHexString(seq3));
System.out.println(store.dump());
assert seq1 == seq3 : "seq1=" + seq1 + ", seq3=" + seq3;
assert seq1 == seq2 : "seq1=" + seq1 + ", seq2=" + seq2;
} else {
/* System.out.println("checked Thread=" + Thread.currentThread().getName() +
" pos: " + position +
" seq1: " + seq1);*/
}
} catch (@NotNull EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
}
return true;
}
@Override
public String toString() {
return "StoreAppender{" +
"queue=" + queue +
", cycle=" + cycle +
", position=" + position +
", lastIndex=" + lastIndex +
", lazyIndexing=" + lazyIndexing +
", lastPosition=" + lastPosition +
", lastCycle=" + lastCycle +
'}';
}
private interface HeaderWriteStrategy {
void onContextClose();
boolean onContextOpen(boolean metaData, int safeLength);
}
class StoreAppenderContext implements DocumentContext {
boolean isClosed;
boolean deferredHeader;
boolean padToCacheAlign = true;
private boolean metaData = false;
private boolean rollbackOnClose = false;
@Nullable
private Wire wire;
@Override
public int sourceId() {
return StoreAppender.this.sourceId();
}
@Override
public boolean isPresent() {
return false;
}
@NotNull
@Override
public Wire wire() {
return wire;
}
@Override
public boolean isMetaData() {
return metaData;
}
@Override
public void metaData(boolean metaData) {
this.metaData = metaData;
}
@Override
public boolean isClosed() {
return isClosed;
}
/**
* Call this if you have detected an error condition and you want the context
* rolled back when it is closed, rather than committed
*/
@Override
public void rollbackOnClose() {
this.rollbackOnClose = true;
}
@Override
public void close() {
if (isClosed) {
LOG.warn("Already Closed, close was called twice.");
return;
}
try {
final boolean interrupted = Thread.currentThread().isInterrupted();
if (rollbackOnClose || interrupted) {
if (interrupted)
LOG.warn("Thread is interrupted. Can't guarantee complete message, so not committing");
// zero out all contents...
for (long i = position + Wires.SPB_HEADER_SIZE; i <= wire.bytes().writePosition(); i++)
wire.bytes().writeByte(i, (byte) 0);
// ...and then the header, as if we had never been here
wire.bytes().writeVolatileInt(position, 0);
wire.bytes().writePosition(position);
((AbstractWire) wire).forceNotInsideHeader();
return;
}
headerWriteStrategy.onContextClose();
if (wire == StoreAppender.this.wire) {
if (padToCacheAlign)
wire.padToCacheAlign();
boolean updatedHeader = false;
for (int i = 0; i < REPEAT_WHILE_ROLLING; i++) {
try {
wire.updateHeader(position, metaData);
updatedHeader = true;
break;
} catch (EOFException theySeeMeRolling) {
cycle = handleRoll(cycle);
}
}
if (!updatedHeader)
throw new IllegalStateException("Unable to roll to the current cycle");
lastPosition = position;
lastCycle = cycle;
if (!metaData) {
lastIndex(wire.headerNumber());
store.writePosition(position);
if (lastIndex != Long.MIN_VALUE)
writeIndexForPosition(lastIndex, position);
else
assert lazyIndexing || lastIndex == Long.MIN_VALUE || checkIndex(lastIndex, position);
}
assert checkWritePositionHeaderNumber();
} else if (wire != null) {
isClosed = true;
assert resetAppendingThread();
writeBytes(wire.headerNumber(), wire.bytes());
wire = StoreAppender.this.wire;
}
} catch (@NotNull StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
} finally {
assert isClosed || resetAppendingThread();
}
}
@Override
public long index() throws IORuntimeException {
if (this.wire.headerNumber() == Long.MIN_VALUE) {
try {
long headerNumber0 = queue.rollCycle().toIndex(cycle, store
.sequenceForPosition(StoreAppender.this, position, false));
assert (((AbstractWire) this.wire).isInsideHeader());
return isMetaData() ? headerNumber0 : headerNumber0 + 1;
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
return isMetaData() ? Long.MIN_VALUE : this.wire.headerNumber() + 1;
}
@Override
public boolean isNotComplete() {
throw new UnsupportedOperationException();
}
}
/**
* Strategise previous behaviour
*/
private class HeaderWriteStrategyOriginal implements HeaderWriteStrategy {
@Override
public boolean onContextOpen(boolean metaData, int safeLength) {
for (int i = 0; i < REPEAT_WHILE_ROLLING; i++) {
try {
assert wire != null;
long pos = store.writeHeader(wire, safeLength, timeoutMS());
position(pos);
context.isClosed = false;
context.rollbackOnClose = false;
context.wire = wire; // Jvm.isDebug() ? acquireBufferWire() : wire;
context.padToCacheAlign = padToCacheAlignMode() != Padding.NEVER;
context.metaData(metaData);
return true;
} catch (EOFException theySeeMeRolling) {
cycle = handleRoll(cycle);
}
}
throw new IllegalStateException("Unable to roll to the current cycle");
}
@Override
public void onContextClose() {
// do nothing
}
}
/**
* Buffered writes while awaiting for other appenders to release the header #403
*/
private class HeaderWriteStrategyDefer implements HeaderWriteStrategy {
@Override
public boolean onContextOpen(boolean metaData, int safeLength) {
assert wire != null;
long pos = store.tryWriteHeader(wire, safeLength);
if (pos != WireOut.TRY_WRITE_HEADER_FAILED) {
position(pos);
context.wire = wire;
context.deferredHeader = false;
} else {
context.wire = acquireBufferWire();
context.deferredHeader = true;
}
context.isClosed = false;
context.rollbackOnClose = false;
context.padToCacheAlign = padToCacheAlignMode() != Padding.NEVER;
context.metaData(metaData);
return true;
}
public void onContextClose() {
if (context.deferredHeader) {
int safeLength = (int) queue.overlapSize();
assert wire != null;
assert wire != context.wire;
for (int i = 0; i < REPEAT_WHILE_ROLLING; i++) {
try {
// TODO: we should be able to write and update the header in one go
long pos = store.writeHeader(wire, safeLength, timeoutMS());
position(pos);
long length = context.wire.bytes().copyTo(wire.bytes());
wire.bytes().writePosition(length + wire.bytes().writePosition());
context.wire = wire;
return;
} catch (EOFException theySeeMeRolling) {
cycle = handleRoll(cycle);
}
}
throw new IllegalStateException("Unable to roll to the current cycle");
}
}
}
}
// *************************************************************************
//
// TAILERS
//
// *************************************************************************
private static final class ClosableResources {
private final SingleChronicleQueue queue;
private volatile Bytes wireReference = null;
private volatile Bytes bufferWireReference = null;
private volatile Bytes wireForIndexReference = null;
private volatile CommonStore storeReference = null;
ClosableResources(final SingleChronicleQueue queue) {
this.queue = queue;
}
private static void releaseIfNotNull(final Bytes bytesReference) {
// Object is no longer reachable, check that it has not already been released
if (bytesReference != null && bytesReference.refCount() > 0) {
bytesReference.release();
}
}
private void releaseResources() {
releaseIfNotNull(wireForIndexReference);
releaseIfNotNull(wireReference);
releaseIfNotNull(bufferWireReference);
// Object is no longer reachable, check that it has not already been released
if (storeReference != null && storeReference.refCount() > 0) {
queue.release(storeReference);
}
}
}
/**
* Tailer
*/
public static class StoreTailer implements ExcerptTailer, SourceContext, ExcerptContext {
static final int INDEXING_LINEAR_SCAN_THRESHOLD = 70;
@NotNull
private final SingleChronicleQueue queue;
private final StoreTailerContext context = new StoreTailerContext();
private final ClosableResources closableResources;
private final MoveToState moveToState = new MoveToState();
long index; // index of the next read.
@Nullable
WireStore store;
private int cycle;
private long timeForNextCycle = Long.MAX_VALUE;
private TailerDirection direction = TailerDirection.FORWARD;
private Wire wireForIndex;
private boolean readAfterReplicaAcknowledged;
@NotNull
private TailerState state = UNINITIALISED;
private long indexAtCreation = Long.MIN_VALUE;
private boolean readingDocumentFound = false;
private boolean shouldUpdateIndex = false;
public StoreTailer(@NotNull final SingleChronicleQueue queue) {
this.queue = queue;
this.setCycle(Integer.MIN_VALUE);
this.index = 0;
queue.addCloseListener(this, StoreTailer::close);
closableResources = new ClosableResources(queue);
queue.ensureThatRollCycleDoesNotConflictWithExistingQueueFiles();
}
private static boolean isReadOnly(Bytes bytes) {
return bytes instanceof MappedBytes &&
((MappedBytes) bytes).isBackingFileReadOnly();
}
@Nullable
public static MessageHistory readHistory(final DocumentContext dc, MessageHistory history) {
final Wire wire = dc.wire();
if (wire == null)
return null;
Object parent = wire.parent();
wire.parent(null);
try {
final Bytes<?> bytes = wire.bytes();
final byte code = bytes.readByte(bytes.readPosition());
history.reset();
return code == (byte) FIELD_NUMBER ?
readHistoryFromBytes(wire, history) :
readHistoryFromWire(wire, history);
} finally {
wire.parent(parent);
}
}
private static MessageHistory readHistoryFromBytes(final Wire wire, MessageHistory history) {
final Bytes<?> bytes = wire.bytes();
if (MESSAGE_HISTORY_METHOD_ID != wire.readEventNumber())
return null;
((BytesMarshallable) history).readMarshallable(bytes);
return history;
}
private static MessageHistory readHistoryFromWire(final Wire wire, MessageHistory history) {
final StringBuilder sb = SBP.acquireStringBuilder();
ValueIn valueIn = wire.read(sb);
if (!MethodReader.HISTORY.contentEquals(sb))
return null;
valueIn.object(history, MessageHistory.class);
return history;
}
@Override
public boolean readDocument(@NotNull ReadMarshallable reader) {
try (@NotNull DocumentContext dc = readingDocument(false)) {
if (!dc.isPresent())
return false;
reader.readMarshallable(dc.wire());
}
return true;
}
@Override
@NotNull
public DocumentContext readingDocument() {
// trying to create an initial document without a direction should not consume a message
if (direction == NONE && (index == indexAtCreation || index == 0) && !readingDocumentFound) {
return NoDocumentContext.INSTANCE;
}
return readingDocument(false);
}
private void close() {
final Wire wire = context.wire();
if (wire != null) {
wire.bytes().release();
}
context.wire(null);
Wire w0 = wireForIndex;
if (w0 != null)
w0.bytes().release();
wireForIndex = null;
if (store != null) {
queue.release(store);
}
store = null;
}
@Override
public Wire wire() {
return context.wire();
}
@Override
public Wire wireForIndex() {
return wireForIndex;
}
@Override
public long timeoutMS() {
return queue.timeoutMS;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@NotNull
@Override
public String toString() {
return "StoreTailer{" +
"index sequence=" + queue.rollCycle().toSequenceNumber(index) +
", index cycle=" + queue.rollCycle().toCycle(index) +
", store=" + store + ", queue=" + queue + '}';
}
@NotNull
@Override
public DocumentContext readingDocument(boolean includeMetaData) {
if (queue.isClosed.get())
throw new IllegalStateException("Queue is closed");
try {
boolean next = false, tryAgain = true;
if (state == FOUND_CYCLE) {
try {
next = inACycle(includeMetaData, true);
tryAgain = false;
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
}
if (tryAgain)
next = next0(includeMetaData);
if (context.present(next)) {
context.setStart(context.wire().bytes().readPosition() - 4);
readingDocumentFound = true;
return context;
}
RollCycle rollCycle = queue.rollCycle();
if (state == CYCLE_NOT_FOUND && direction == FORWARD) {
int firstCycle = queue.firstCycle();
if (rollCycle.toCycle(index) < firstCycle)
toStart();
} else if (!next && state == CYCLE_NOT_FOUND && cycle != queue.cycle()) {
// appenders have moved on, it's possible that linearScan is hitting EOF, which is ignored
// since we can't find an entry at current index, indicate that we're at the end of a cycle
state = TailerState.END_OF_CYCLE;
}
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} catch (UnrecoverableTimeoutException notComplete) {
// so treat as empty.
} catch (DecoratedBufferUnderflowException e) {
// read-only tailer view is fixed, a writer could continue past the end of the view
// at the point this tailer was created. Log a warning and return no document.
if (queue.isReadOnly()) {
Jvm.warn().on(StoreTailer.class, "Tried to read past the end of a read-only view. " +
"Underlying data store may have grown since this tailer was created.", e);
} else {
throw e;
}
}
return NoDocumentContext.INSTANCE;
}
private boolean next0(boolean includeMetaData) throws UnrecoverableTimeoutException, StreamCorruptedException {
for (int i = 0; i < 1000; i++) {
switch (state) {
case UNINITIALISED:
final long firstIndex = queue.firstIndex();
if (firstIndex == Long.MAX_VALUE)
return false;
if (!moveToIndexInternal(firstIndex))
return false;
break;
case FOUND_CYCLE: {
try {
return inACycle(includeMetaData, true);
} catch (EOFException eof) {
state = TailerState.END_OF_CYCLE;
}
break;
}
case END_OF_CYCLE:
if (endOfCycle())
continue;
return false;
case BEYOND_START_OF_CYCLE:
if (beyondStartOfCycle())
continue;
return false;
case CYCLE_NOT_FOUND:
if (nextCycleNotFound())
continue;
return false;
default:
throw new AssertionError("state=" + state);
}
}
throw new IllegalStateException("Unable to progress to the next cycle, state=" + state);
}
private boolean endOfCycle() {
long oldIndex = this.index;
int currentCycle = queue.rollCycle().toCycle(oldIndex);
long nextIndex = nextIndexWithNextAvailableCycle(currentCycle);
if (nextIndex != Long.MIN_VALUE) {
if (nextEndOfCycle(nextIndex))
return true;
} else {
state = END_OF_CYCLE;
}
return false;
}
private boolean beyondStartOfCycle() throws StreamCorruptedException {
if (direction == FORWARD) {
state = UNINITIALISED;
return true;
} else if (direction == BACKWARD) {
return beyondStartOfCycleBackward();
}
throw new AssertionError("direction not set, direction=" + direction);
}
private boolean nextEndOfCycle(long nextIndex) {
if (moveToIndexInternal(nextIndex)) {
state = FOUND_CYCLE;
return true;
}
if (state == END_OF_CYCLE)
return true;
if (cycle < queue.lastCycle()) {
// we have encountered an empty file without an EOF marker
// TODO: more work needed - I thought that the appender and/or tailer would write an EOF into this file
state = END_OF_CYCLE;
return true;
}
// We are here because we are waiting for an entry to be written to this file.
// Winding back to the previous cycle results in a re-initialisation of all the objects => garbage
int nextCycle = queue.rollCycle().toCycle(nextIndex);
cycle(nextCycle, false);
state = CYCLE_NOT_FOUND;
return false;
}
private boolean beyondStartOfCycleBackward() throws StreamCorruptedException {
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
boolean foundCycle = cycle(queue.rollCycle().toCycle(index), false);
if (foundCycle) {
long lastSequenceNumberInThisCycle = store().sequenceForPosition(this, Long.MAX_VALUE, false);
long nextIndex = queue.rollCycle().toIndex(this.cycle,
lastSequenceNumberInThisCycle);
moveToIndexInternal(nextIndex);
state = FOUND_CYCLE;
return true;
}
int cycle = queue.rollCycle().toCycle(index);
long nextIndex = nextIndexWithNextAvailableCycle(cycle);
if (nextIndex != Long.MIN_VALUE) {
moveToIndexInternal(nextIndex);
state = FOUND_CYCLE;
return true;
}
state = BEYOND_START_OF_CYCLE;
return false;
}
private boolean nextCycleNotFound() {
if (index == Long.MIN_VALUE) {
if (this.store != null)
queue.release(this.store);
this.store = null;
closableResources.storeReference = null;
return false;
}
if (moveToIndexInternal(index)) {
state = FOUND_CYCLE;
return true;
}
return false;
}
private boolean inACycle(boolean includeMetaData, boolean first)
throws EOFException, StreamCorruptedException {
Wire wire = wire();
Bytes<?> bytes = wire.bytes();
bytes.readLimit(bytes.capacity());
if (readAfterReplicaAcknowledged && inACycleCheckRep()) return false;
if (direction != TailerDirection.FORWARD && inACycleNotForward()) return false;
switch (wire.readDataHeader(includeMetaData)) {
case NONE:
return inACycleNone(includeMetaData, first, bytes);
case META_DATA:
context.metaData(true);
break;
case DATA:
context.metaData(false);
break;
}
inACycleFound(bytes);
return true;
}
private boolean inACycleCheckRep() {
long lastSequenceAck = store().lastAcknowledgedIndexReplicated();
long seq = queue.rollCycle().toSequenceNumber(index);
return seq > lastSequenceAck;
}
private boolean inACycleNotForward() {
if (!moveToIndexInternal(index)) {
try {
// after toEnd() call, index is past the end of the queue
// so try to go back one (to the last record in the queue)
if (!moveToIndexInternal(index - 1)) {
return true;
}
} catch (RuntimeException e) {
// can happen if index goes negative
return true;
}
}
return false;
}
private void inACycleFound(Bytes<?> bytes) throws StreamCorruptedException {
indexEntry(bytes);
context.closeReadLimit(bytes.capacity());
wire().readAndSetLength(bytes.readPosition());
long end = bytes.readLimit();
context.closeReadPosition(end);
}
private boolean inACycleNone(boolean includeMetaData, boolean first, Bytes<?> bytes) throws EOFException, StreamCorruptedException {
// if current time is not the current cycle, then write an EOF marker and
// re-read from here, you may find that in the mean time an appender writes
// another message, however the EOF marker will always be at the end.
long now = queue.time().currentTimeMillis();
boolean cycleChange2 = now >= timeForNextCycle;
return first
&& cycleChange2
&& !isReadOnly(bytes)
&& checkMoveToNextCycle(includeMetaData, bytes);
}
private void indexEntry(@NotNull Bytes<?> bytes) throws StreamCorruptedException {
if (store().indexable(index)
&& shouldUpdateIndex
&& direction == TailerDirection.FORWARD
&& !context.isMetaData())
store.setPositionForSequenceNumber(this,
queue.rollCycle().toSequenceNumber(index), bytes
.readPosition());
}
private boolean checkMoveToNextCycle(boolean includeMetaData, @NotNull Bytes<?> bytes)
throws EOFException, StreamCorruptedException {
if (bytes.readWrite()) {
long pos = bytes.readPosition();
long lim = bytes.readLimit();
long wlim = bytes.writeLimit();
try {
bytes.writePosition(pos);
store.writeEOF(wire(), timeoutMS());
} finally {
bytes.writeLimit(wlim);
bytes.readLimit(lim);
bytes.readPosition(pos);
}
} else {
Jvm.debug().on(getClass(), "Unable to append EOF to ReadOnly store, skipping");
// even though we couldn't write EOF, we still need to indicate we're at EOF to prevent looping forever
// only do that if we waited long enough to prevent terminating too early
long now = queue.time().currentTimeMillis();
if (now >= timeForNextCycle + timeoutMS() * 2)
throw new EOFException();
}
return inACycle(includeMetaData, false);
}
private long nextIndexWithNextAvailableCycle(int cycle) {
if (cycle == Integer.MIN_VALUE)
throw new AssertionError("cycle == Integer.MIN_VALUE");
long nextIndex, doubleCheck;
// DON'T REMOVE THIS DOUBLE CHECK - ESPECIALLY WHEN USING SECONDLY THE
// FIRST RESULT CAN DIFFER FROM THE DOUBLE CHECK, AS THE APPENDER CAN RACE WITH THE
// TAILER
do {
nextIndex = nextIndexWithNextAvailableCycle0(cycle);
if (nextIndex != Long.MIN_VALUE) {
int nextCycle = queue.rollCycle().toCycle(nextIndex);
if (nextCycle == cycle + 1) {
// don't do the double check if the next cycle is adjacent to the current
return nextIndex;
}
}
doubleCheck = nextIndexWithNextAvailableCycle0(cycle);
} while (nextIndex != doubleCheck);
if (nextIndex != Long.MIN_VALUE && queue.rollCycle().toCycle(nextIndex) - 1 != cycle) {
/*
* lets say that you were using a roll cycle of TEST_SECONDLY
* and you wrote a message to the queue, if you created a tailer and read the first message,
* then waited around 22 seconds before writing the next message, when the tailer
* came to read the next message, there would be a gap of 22 cycle files
* that did not exist, that is what this is reporting. If you are using daily rolling,
* and writing every day, you should not see this message.
*/
LOG.debug("Rolled " + (queue
.rollCycle().toCycle(nextIndex) - cycle) + " " + "times to find the " +
"next cycle file. This can occur if your appenders have not written " +
"anything for a while, leaving the cycle files with a gap.");
}
return nextIndex;
}
private long nextIndexWithNextAvailableCycle0(int cycle) {
if (cycle > queue.lastCycle() || direction == TailerDirection.NONE) {
return Long.MIN_VALUE;
}
int nextCycle = cycle + direction.add();
boolean found = cycle(nextCycle, false);
if (found)
return nextIndexWithinFoundCycle(nextCycle);
try {
int nextCycle0 = queue.nextCycle(this.cycle, direction);
if (nextCycle0 == -1)
return Long.MIN_VALUE;
return nextIndexWithinFoundCycle(nextCycle0);
} catch (ParseException e) {
throw new IllegalStateException(e);
}
}
private long nextIndexWithinFoundCycle(int nextCycle) {
state = FOUND_CYCLE;
if (direction == FORWARD)
return queue.rollCycle().toIndex(nextCycle, 0);
if (direction == BACKWARD) {
try {
long lastSequenceNumber0 = store().lastSequenceNumber(this);
return queue.rollCycle().toIndex(nextCycle, lastSequenceNumber0);
} catch (Exception e) {
throw new AssertionError(e);
}
} else {
throw new IllegalStateException("direction=" + direction);
}
}
/**
* @return provides an index that includes the cycle number
*/
@Override
public long index() {
return this.index;
}
@Override
public int cycle() {
return this.cycle;
}
@Override
public boolean moveToIndex(final long index) {
if (moveToState.canReuseLastIndexMove(index, state, direction, queue, wire())) {
return true;
} else if (moveToState.indexIsCloseToAndAheadOfLastIndexMove(index, state, direction, queue)) {
final long knownIndex = moveToState.lastMovedToIndex;
final boolean found =
this.store.linearScanTo(index, knownIndex, this,
moveToState.readPositionAtLastMove) == ScanResult.FOUND;
if (found) {
index(index);
moveToState.onSuccessfulScan(index, direction, wire().bytes().readPosition());
}
return found;
}
return moveToIndexInternal(index);
}
ScanResult moveToIndexResult(long index) {
final int cycle = queue.rollCycle().toCycle(index);
final long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
if (LOG.isTraceEnabled()) {
Jvm.debug().on(getClass(), "moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (cycle != this.cycle || state != FOUND_CYCLE) {
// moves to the expected cycle
if (!cycle(cycle, false))
return ScanResult.NOT_REACHED;
}
index(index);
ScanResult scanResult = this.store().moveToIndexForRead(this, sequenceNumber);
Bytes<?> bytes = wire().bytes();
if (scanResult == FOUND) {
state = FOUND_CYCLE;
moveToState.onSuccessfulLookup(index, direction, bytes.readPosition());
return scanResult;
} else if (scanResult == END_OF_FILE) {
state = END_OF_CYCLE;
return scanResult;
} else if (scanResult == NOT_FOUND && this.cycle < this.queue.lastCycle) {
state = END_OF_CYCLE;
return END_OF_FILE;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@NotNull
@Override
public final ExcerptTailer toStart() {
assert direction != BACKWARD;
final int firstCycle = queue.firstCycle();
if (firstCycle == Integer.MAX_VALUE) {
state = UNINITIALISED;
return this;
}
if (firstCycle != this.cycle) {
// moves to the expected cycle
boolean found = cycle(firstCycle, false);
assert found || store == null;
if (found)
state = FOUND_CYCLE;
}
index(queue.rollCycle().toIndex(cycle, 0));
state = FOUND_CYCLE;
if (wire() != null)
wire().bytes().readPosition(0);
return this;
}
private boolean moveToIndexInternal(final long index) {
moveToState.indexMoveCount++;
final ScanResult scanResult = moveToIndexResult(index);
return scanResult == FOUND;
}
/**
* gives approximately the last index, can not be relied on as the last index may have
* changed just after this was called. For this reason, this code is not in queue as it
* should only be an internal method
*
* @return the last index at the time this method was called, or Long.MIN_VALUE if none.
*/
private long approximateLastIndex() {
RollCycle rollCycle = queue.rollCycle();
final int lastCycle = queue.lastCycle();
try {
if (lastCycle == Integer.MIN_VALUE)
return Long.MIN_VALUE;
final WireStore wireStore = queue.storeForCycle(lastCycle, queue.epoch(), false);
this.setCycle(lastCycle);
if (wireStore == null)
throw new IllegalStateException("Store not found for cycle " + Long.toHexString(lastCycle) + ". Probably the files were removed?");
if (store != null)
queue.release(store);
if (this.store != wireStore) {
this.store = wireStore;
closableResources.storeReference = wireStore;
resetWires();
}
// give the position of the last entry and
// flag we want to count it even though we don't know if it will be meta data or not.
long sequenceNumber = store.lastSequenceNumber(this);
// fixes #378
if (sequenceNumber == -1L) {
// nothing has been written yet, so point to start of cycle
return rollCycle.toIndex(lastCycle, 0L);
}
return rollCycle.toIndex(lastCycle, sequenceNumber);
} catch (@NotNull StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
}
}
private boolean headerNumberCheck(@NotNull AbstractWire wire) {
wire.headNumberCheck((actual, position) -> {
try {
long expecting = store.sequenceForPosition(this, position, false);
if (actual == expecting)
return true;
LOG.error("", new AssertionError("header number check failed " +
"expecting=" + expecting +
" != actual=" + actual));
return false;
} catch (Exception e) {
LOG.error("", e);
return false;
}
});
return true;
}
private void resetWires() {
WireType wireType = queue.wireType();
final AbstractWire wire = (AbstractWire) readAnywhere(wireType.apply(store().bytes()));
assert headerNumberCheck(wire);
this.context.wire(wire);
wire.parent(this);
Wire wireForIndexOld = wireForIndex;
wireForIndex = readAnywhere(wireType.apply(store().bytes()));
closableResources.wireForIndexReference = wireForIndex.bytes();
closableResources.wireReference = wire.bytes();
assert headerNumberCheck((AbstractWire) wireForIndex);
if (wireForIndexOld != null) {
releaseWireResources(wireForIndexOld);
}
}
@NotNull
private Wire readAnywhere(@NotNull Wire wire) {
Bytes<?> bytes = wire.bytes();
bytes.readLimit(bytes.capacity());
return wire;
}
@NotNull
@Override
public ExcerptTailer toEnd() {
long index = approximateLastIndex();
if (index == Long.MIN_VALUE) {
if (state() == TailerState.CYCLE_NOT_FOUND)
state = UNINITIALISED;
return this;
}
final ScanResult scanResult = moveToIndexResult(index);
switch (scanResult) {
case NOT_FOUND:
if (moveToIndexResult(index - 1) == FOUND)
state = FOUND_CYCLE;
break;
case FOUND:
if (direction == FORWARD) {
final ScanResult result = moveToIndexResult(++index);
switch (result) {
case FOUND:
// the end moved!!
state = FOUND_CYCLE;
break;
case NOT_REACHED:
throw new IllegalStateException("NOT_REACHED after FOUND");
case NOT_FOUND:
state = FOUND_CYCLE;
break;
case END_OF_FILE:
state = END_OF_CYCLE;
break;
default:
throw new IllegalStateException("Unknown ScanResult: " + result);
}
}
break;
case NOT_REACHED:
approximateLastIndex();
throw new IllegalStateException("NOT_REACHED index: " + Long.toHexString(index));
case END_OF_FILE:
state = END_OF_CYCLE;
break;
default:
throw new IllegalStateException("Unknown ScanResult: " + scanResult);
}
return this;
}
@Override
public TailerDirection direction() {
return direction;
}
@NotNull
@Override
public ExcerptTailer direction(TailerDirection direction) {
final TailerDirection oldDirection = this.direction();
this.direction = direction;
if (oldDirection == TailerDirection.BACKWARD &&
direction == TailerDirection.FORWARD) {
moveToIndexInternal(index);
}
return this;
}
@Override
@NotNull
public RollingChronicleQueue queue() {
return queue;
}
@Override
public Runnable getCloserJob() {
return closableResources::releaseResources;
}
/**
* Can be used to manually release resources when this
* StoreTailer is no longer used.
*/
public void releaseResources() {
queue.removeCloseListener(this);
getCloserJob().run();
}
private void incrementIndex() {
RollCycle rollCycle = queue.rollCycle();
long seq = rollCycle.toSequenceNumber(this.index);
int cycle = rollCycle.toCycle(this.index);
seq += direction.add();
switch (direction) {
case NONE:
break;
case FORWARD:
// if it runs out of seq number it will flow over to tomorrows cycle file
if (rollCycle.toSequenceNumber(seq) < seq) {
cycle(cycle + 1, false);
LOG.warn("we have run out of sequence numbers, so will start to write to " +
"the next .cq4 file, the new cycle=" + cycle);
seq = 0;
}
break;
case BACKWARD:
if (seq < 0) {
windBackCycle(cycle);
return;
}
break;
}
this.index = rollCycle.toIndex(cycle, seq);
}
private void windBackCycle(int cycle) {
if (tryWindBack(cycle - 1))
return;
cycle--;
for (long first = queue.firstCycle(); cycle >= first; cycle--) {
if (tryWindBack(cycle))
return;
}
this.index(queue.rollCycle().toIndex(cycle, -1));
this.state = BEYOND_START_OF_CYCLE;
}
private boolean tryWindBack(int cycle) {
long count = queue.exceptsPerCycle(cycle);
if (count <= 0)
return false;
RollCycle rollCycle = queue.rollCycle();
moveToIndexInternal(rollCycle.toIndex(cycle, count - 1));
this.state = FOUND_CYCLE;
return true;
}
// DON'T INLINE THIS METHOD, as it's used by enterprise chronicle queue
void index(long index) {
this.index = index;
if (indexAtCreation == Long.MIN_VALUE) {
indexAtCreation = index;
}
moveToState.reset();
}
private boolean cycle(final int cycle, boolean createIfAbsent) {
if (this.cycle == cycle && state == FOUND_CYCLE)
return true;
WireStore nextStore = this.queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
if (nextStore == null && this.store == null)
return false;
if (nextStore == null) {
if (direction == BACKWARD)
state = BEYOND_START_OF_CYCLE;
else
state = CYCLE_NOT_FOUND;
return false;
}
if (store != null)
queue.release(store);
if (nextStore == this.store)
return true;
context.wire(null);
this.store = nextStore;
closableResources.storeReference = nextStore;
this.state = FOUND_CYCLE;
this.setCycle(cycle);
resetWires();
final Wire wire = wire();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
return true;
}
void release() {
if (store != null) {
queue.release(store);
store = null;
closableResources.storeReference = null;
}
state = UNINITIALISED;
}
@Override
public void readAfterReplicaAcknowledged(boolean readAfterReplicaAcknowledged) {
this.readAfterReplicaAcknowledged = readAfterReplicaAcknowledged;
}
@Override
public boolean readAfterReplicaAcknowledged() {
return readAfterReplicaAcknowledged;
}
@NotNull
@Override
public TailerState state() {
return state;
}
@NotNull
@Override
public ExcerptTailer afterLastWritten(@NotNull ChronicleQueue queue) {
if (queue == this.queue)
throw new IllegalArgumentException("You must pass the queue written to, not the queue read");
@NotNull ExcerptTailer tailer = queue.createTailer()
.direction(BACKWARD)
.toEnd();
@NotNull VanillaMessageHistory messageHistory = new VanillaMessageHistory();
while (true) {
try (DocumentContext context = tailer.readingDocument()) {
if (!context.isData()) {
toStart();
return this;
}
MessageHistory veh = readHistory(context, messageHistory);
if (veh == null)
continue;
int i = veh.sources() - 1;
if (i < 0)
continue;
if (veh.sourceId(i) != this.sourceId())
continue;
long sourceIndex = veh.sourceIndex(i);
if (!moveToIndexInternal(sourceIndex)) {
final String errorMessage = String.format(
"Unable to move to sourceIndex %s in queue %s",
Long.toHexString(sourceIndex), this.queue.fileAbsolutePath());
throw new IORuntimeException(errorMessage + extraInfo(tailer, messageHistory));
}
try (DocumentContext content = readingDocument()) {
if (!content.isPresent()) {
final String errorMessage = String.format(
"No readable document found at sourceIndex %s in queue %s",
Long.toHexString(sourceIndex + 1), this.queue.fileAbsolutePath());
throw new IORuntimeException(errorMessage + extraInfo(tailer, messageHistory));
}
// skip this message and go to the next.
}
return this;
}
}
}
private String extraInfo(@NotNull ExcerptTailer tailer, @NotNull VanillaMessageHistory messageHistory) {
return String.format(
". That sourceIndex was determined fom the last entry written to queue %s " +
"(message index %s, message history %s). If source queue is replicated then " +
"sourceIndex may not have been replicated yet",
tailer.queue().fileAbsolutePath(), Long.toHexString(tailer.index()), WireType.TEXT.asString(messageHistory));
}
@NotNull
@Override
public ExcerptTailer indexing(final boolean indexing) {
this.shouldUpdateIndex = indexing;
return this;
}
public void lastAcknowledgedIndexReplicated(long acknowledgeIndex) {
if (Jvm.isDebugEnabled(getClass()))
Jvm.debug().on(getClass(), "received lastAcknowledgedIndexReplicated=" + Long.toHexString(acknowledgeIndex) + " ,file=" + queue().fileAbsolutePath());
RollCycle rollCycle = queue.rollCycle();
int cycle0 = rollCycle.toCycle(acknowledgeIndex);
// cycle is the same so the same tailer can be used.
if (cycle0 == cycle()) {
store.lastAcknowledgedIndexReplicated(acknowledgeIndex);
return;
}
// the reason that we use the temp tailer is to prevent this tailer from having its cycle changed
// NOTE: This is a very expensive operation.
StoreTailer temp = queue.acquireTailer();
try {
if (!temp.cycle(cycle0, false)) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(acknowledgeIndex) + " for a cycle which could not found");
return;
}
WireStore store = temp.store;
if (store == null) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(acknowledgeIndex) + " discarded.");
return;
}
store.lastAcknowledgedIndexReplicated(acknowledgeIndex);
} finally {
temp.release();
}
}
public void lastIndexReplicated(long lastIndexReplicated) {
if (Jvm.isDebugEnabled(getClass()))
Jvm.debug().on(getClass(), "received lastIndexReplicated=" + Long.toHexString(lastIndexReplicated) + " ,file=" + queue().fileAbsolutePath());
RollCycle rollCycle = queue.rollCycle();
int cycle0 = rollCycle.toCycle(lastIndexReplicated);
// cycle is the same so the same tailer can be used.
if (cycle0 == cycle()) {
store().lastIndexReplicated(lastIndexReplicated);
return;
}
// the reason that we use the temp tailer is to prevent this tailer from having its cycle changed
// NOTE: This is a very expensive operation.
StoreTailer temp = queue.acquireTailer();
try {
if (!temp.cycle(cycle0, false)) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(lastIndexReplicated) + " for a cycle which could not found");
return;
}
if (temp.store == null) {
Jvm.warn().on(getClass(), "Got an acknowledge index " + Long.toHexString(lastIndexReplicated) + " discarded.");
return;
}
temp.store().lastIndexReplicated(lastIndexReplicated);
} finally {
temp.release();
}
}
public long lastAcknowledgedIndexReplicated() {
return ((StoreAppender) queue.acquireAppender()).store().lastAcknowledgedIndexReplicated();
}
public long lastIndexReplicated() {
return ((StoreAppender) queue.acquireAppender()).store().lastIndexReplicated();
}
public void setCycle(int cycle) {
this.cycle = cycle;
timeForNextCycle = cycle == Integer.MIN_VALUE ? Long.MAX_VALUE :
(long) (cycle + 1) * queue.rollCycle().length() + queue.epoch();
}
// visible for testing
int getIndexMoveCount() {
return moveToState.indexMoveCount;
}
@NotNull
public WireStore store() {
if (store == null)
setCycle(cycle());
return store;
}
private static final class MoveToState {
private long lastMovedToIndex = Long.MIN_VALUE;
private TailerDirection directionAtLastMoveTo = TailerDirection.NONE;
private long readPositionAtLastMove = Long.MIN_VALUE;
private int indexMoveCount = 0;
void onSuccessfulLookup(
final long movedToIndex, final TailerDirection direction,
final long readPosition) {
this.lastMovedToIndex = movedToIndex;
this.directionAtLastMoveTo = direction;
this.readPositionAtLastMove = readPosition;
}
void onSuccessfulScan(
final long movedToIndex, final TailerDirection direction,
final long readPosition) {
this.lastMovedToIndex = movedToIndex;
this.directionAtLastMoveTo = direction;
this.readPositionAtLastMove = readPosition;
}
void reset() {
lastMovedToIndex = Long.MIN_VALUE;
directionAtLastMoveTo = TailerDirection.NONE;
readPositionAtLastMove = Long.MIN_VALUE;
}
private boolean indexIsCloseToAndAheadOfLastIndexMove(
final long index, final TailerState state, final TailerDirection direction,
final SingleChronicleQueue queue) {
return lastMovedToIndex != Long.MIN_VALUE &&
index - lastMovedToIndex < INDEXING_LINEAR_SCAN_THRESHOLD &&
state == FOUND_CYCLE &&
direction == directionAtLastMoveTo &&
queue.rollCycle().toCycle(index) == queue.rollCycle().toCycle(lastMovedToIndex) &&
index > lastMovedToIndex;
}
private boolean canReuseLastIndexMove(
final long index, final TailerState state, final TailerDirection direction,
final SingleChronicleQueue queue, final Wire wire) {
return ((wire == null) || wire.bytes().readPosition() == readPositionAtLastMove) &&
index == this.lastMovedToIndex && index != 0 && state == FOUND_CYCLE &&
direction == directionAtLastMoveTo &&
queue.rollCycle().toCycle(index) == queue.rollCycle().toCycle(lastMovedToIndex);
}
}
class StoreTailerContext extends BinaryReadDocumentContext {
boolean rollbackOnClose = false;
StoreTailerContext() {
super(null);
}
@Override
public void rollbackOnClose() {
rollbackOnClose = true;
}
@Override
public long index() {
return StoreTailer.this.index();
}
@Override
public int sourceId() {
return StoreTailer.this.sourceId();
}
@Override
public void close() {
try {
if (rollbackOnClose) {
present = false;
if (start != -1)
wire.bytes().readPosition(start).readLimit(readLimit);
start = -1;
return;
}
if (isPresent() && !isMetaData())
incrementIndex();
super.close();
// assert wire == null || wire.endUse();
} finally {
rollbackOnClose = false;
}
}
boolean present(boolean present) {
return this.present = present;
}
public void wire(@Nullable AbstractWire wire) {
AbstractWire oldWire = this.wire;
this.wire = wire;
if (oldWire != null) {
releaseWireResources(oldWire);
}
}
}
}
} | https://github.com/OpenHFT/Chronicle-Queue/issues/484 code cleanups
| src/main/java/net/openhft/chronicle/queue/impl/single/SingleChronicleQueueExcerpts.java | https://github.com/OpenHFT/Chronicle-Queue/issues/484 code cleanups | <ide><path>rc/main/java/net/openhft/chronicle/queue/impl/single/SingleChronicleQueueExcerpts.java
<ide> }
<ide>
<ide> /**
<del> * this is not currently thread safe so should be run on the same thread as the appender
<add> * this method NOT thread safe
<ide> */
<ide> @Override
<ide> public void pretouch() {
<ide> try {
<ide> int qCycle = queue.cycle();
<ide> setCycle(qCycle);
<del> WireStore store = this.store;
<del> if (store == null || store.bytes().isClosed())
<del> return;
<add>
<ide> if (pretoucher == null)
<del> pretoucher = new PretoucherState(store::writePosition);
<add> pretoucher = new PretoucherState(this.store::writePosition);
<ide>
<ide> Wire wire = this.wire;
<del> if (wire != null && wire.bytes().bytesStore().refCount() > 0)
<add> if (wire != null)
<ide> pretoucher.pretouch((MappedBytes) wire.bytes());
<ide>
<ide> if (pretouchStore != null && pretouchCycle == qCycle) {
<ide> releasePretouchStore();
<del> } else {
<del>
<del> int pretouchCycle0 = queue.cycle(pretouchTimeProvider);
<del>
<del> if (pretouchCycle0 != qCycle && pretouchCycle != pretouchCycle0) {
<del> releasePretouchStore();
<del>
<del> pretouchStore = queue.storeSupplier().acquire(pretouchCycle0, true);
<del> pretouchCycle = pretouchCycle0;
<del> pretoucher = null;
<del> if (Jvm.isDebugEnabled(getClass()))
<del> Jvm.debug().on(getClass(), "Pretoucher ROLLING to next file=" +
<del> pretouchStore.file());
<del> }
<del> }
<add> return;
<add> }
<add>
<add> int pretouchCycle0 = queue.cycle(pretouchTimeProvider);
<add>
<add> if (pretouchCycle0 != qCycle && pretouchCycle != pretouchCycle0) {
<add> releasePretouchStore();
<add> pretouchStore = queue.storeSupplier().acquire(pretouchCycle0, true);
<add> pretouchCycle = pretouchCycle0;
<add> pretoucher = null;
<add> if (Jvm.isDebugEnabled(getClass()))
<add> Jvm.debug().on(getClass(), "Pretoucher ROLLING to next file=" +
<add> pretouchStore.file());
<add> }
<add>
<ide> } catch (Throwable e) {
<del> e.printStackTrace();
<ide> Jvm.warn().on(getClass(), e);
<ide> }
<ide> }
<ide> pretouchStore.release();
<ide> pretouchCycle = -1;
<ide> this.pretouchStore = null;
<del>
<ide> }
<ide>
<ide> @Nullable |
|
Java | apache-2.0 | d2a92064378d1fbe220c5d56607d89af4386948f | 0 | cushon/bazel,bazelbuild/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,perezd/bazel,dslomov/bazel,meteorcloudy/bazel,katre/bazel,katre/bazel,meteorcloudy/bazel,meteorcloudy/bazel,twitter-forks/bazel,twitter-forks/bazel,perezd/bazel,twitter-forks/bazel,cushon/bazel,werkt/bazel,meteorcloudy/bazel,ButterflyNetwork/bazel,davidzchen/bazel,safarmer/bazel,ButterflyNetwork/bazel,davidzchen/bazel,werkt/bazel,safarmer/bazel,aehlig/bazel,ulfjack/bazel,dslomov/bazel,cushon/bazel,werkt/bazel,akira-baruah/bazel,aehlig/bazel,davidzchen/bazel,akira-baruah/bazel,aehlig/bazel,dslomov/bazel-windows,twitter-forks/bazel,dslomov/bazel,aehlig/bazel,dslomov/bazel-windows,werkt/bazel,ulfjack/bazel,dslomov/bazel,meteorcloudy/bazel,davidzchen/bazel,twitter-forks/bazel,perezd/bazel,bazelbuild/bazel,bazelbuild/bazel,bazelbuild/bazel,safarmer/bazel,twitter-forks/bazel,dslomov/bazel,davidzchen/bazel,safarmer/bazel,bazelbuild/bazel,katre/bazel,ButterflyNetwork/bazel,ulfjack/bazel,akira-baruah/bazel,bazelbuild/bazel,perezd/bazel,twitter-forks/bazel,dslomov/bazel-windows,meteorcloudy/bazel,aehlig/bazel,davidzchen/bazel,cushon/bazel,ulfjack/bazel,cushon/bazel,meteorcloudy/bazel,davidzchen/bazel,ulfjack/bazel,aehlig/bazel,dslomov/bazel,perezd/bazel,katre/bazel,akira-baruah/bazel,perezd/bazel,werkt/bazel,dslomov/bazel-windows,aehlig/bazel,katre/bazel,cushon/bazel,ulfjack/bazel,dslomov/bazel-windows,safarmer/bazel,perezd/bazel,dslomov/bazel,akira-baruah/bazel,katre/bazel,safarmer/bazel,dslomov/bazel-windows,akira-baruah/bazel,werkt/bazel,ButterflyNetwork/bazel,ulfjack/bazel | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar.runtime;
import android.app.PendingIntent;
import android.app.usage.UsageStatsManager;
import java.util.concurrent.TimeUnit;
/**
* Conversions for hidden Android APIs that use desugared primitives (see b/79121791). These are
* grouped into a separate class to simplify building with them, since they use APIs that are
* omitted in the android.jar.
*/
@SuppressWarnings("AndroidApiChecker")
public final class HiddenConversions {
private HiddenConversions() {} // static methods only
public static j$.time.LocalDate getLocalDate(
android.hardware.display.AmbientBrightnessDayStats stats) {
return fromLocalDate(stats.getLocalDate());
}
private static j$.time.LocalDate fromLocalDate(java.time.LocalDate date) {
if (date == null) {
return null;
}
return j$.time.LocalDate.of(date.getYear(), date.getMonthValue(), date.getDayOfMonth());
}
public static void registerAppUsageLimitObserver(
UsageStatsManager receiver,
int observerId,
String[] observedEntities,
j$.time.Duration timeLimit,
j$.time.Duration timeUsed,
PendingIntent callbackIntent) {
receiver.registerAppUsageLimitObserver(
observerId, observedEntities, toDuration(timeLimit), toDuration(timeUsed), callbackIntent);
}
public static void registerUsageSessionObserver(
UsageStatsManager receiver,
int sessionObserverId,
String[] observedEntities,
j$.time.Duration timeLimit,
j$.time.Duration sessionThresholdTime,
PendingIntent limitReachedCallbackIntent,
PendingIntent sessionEndCallbackIntent) {
receiver.registerUsageSessionObserver(
sessionObserverId,
observedEntities,
toDuration(timeLimit),
toDuration(sessionThresholdTime),
limitReachedCallbackIntent,
sessionEndCallbackIntent);
}
public static void registerUsageSessionObserver(
UsageStatsManager receiver,
int sessionObserverId,
String[] observedEntities,
long timeLimit,
TimeUnit timeLimitUnit,
long sessionThreshold,
TimeUnit sessionThresholdUnit,
PendingIntent limitReachedCallbackIntent,
PendingIntent sessionEndCallbackIntent) {
receiver.registerUsageSessionObserver(
sessionObserverId,
observedEntities,
java.time.Duration.ofMillis(timeLimitUnit.toMillis(timeLimit)),
java.time.Duration.ofMillis(sessionThresholdUnit.toMillis(sessionThreshold)),
limitReachedCallbackIntent,
sessionEndCallbackIntent);
}
private static java.time.Duration toDuration(j$.time.Duration duration) {
if (duration == null) {
return null;
}
return java.time.Duration.ofSeconds(duration.getSeconds(), duration.getNano());
}
}
| src/tools/android/java/com/google/devtools/build/android/desugar/runtime/HiddenConversions.java | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar.runtime;
import android.app.PendingIntent;
import android.app.usage.UsageStatsManager;
import java.util.concurrent.TimeUnit;
/**
* Conversions for hidden Android APIs that use desugared primitives (see b/79121791). These are
* grouped into a separate class to simplify building with them, since they use APIs that are
* omitted in the android.jar.
*/
@SuppressWarnings("AndroidApiChecker")
public final class HiddenConversions {
private HiddenConversions() {} // static methods only
public static j$.time.LocalDate getLocalDate(
android.hardware.display.AmbientBrightnessDayStats stats) {
return fromLocalDate(stats.getLocalDate());
}
private static j$.time.LocalDate fromLocalDate(java.time.LocalDate date) {
if (date == null) {
return null;
}
return j$.time.LocalDate.of(date.getYear(), date.getMonthValue(), date.getDayOfMonth());
}
public static void registerUsageSessionObserver(
UsageStatsManager receiver,
int sessionObserverId,
String[] observedEntities,
j$.time.Duration timeLimit,
j$.time.Duration sessionThresholdTime,
PendingIntent limitReachedCallbackIntent,
PendingIntent sessionEndCallbackIntent) {
receiver.registerUsageSessionObserver(
sessionObserverId,
observedEntities,
toDuration(timeLimit),
toDuration(sessionThresholdTime),
limitReachedCallbackIntent,
sessionEndCallbackIntent);
}
public static void registerUsageSessionObserver(
UsageStatsManager receiver,
int sessionObserverId,
String[] observedEntities,
long timeLimit,
TimeUnit timeLimitUnit,
long sessionThreshold,
TimeUnit sessionThresholdUnit,
PendingIntent limitReachedCallbackIntent,
PendingIntent sessionEndCallbackIntent) {
receiver.registerUsageSessionObserver(
sessionObserverId,
observedEntities,
java.time.Duration.ofMillis(timeLimitUnit.toMillis(timeLimit)),
java.time.Duration.ofMillis(sessionThresholdUnit.toMillis(sessionThreshold)),
limitReachedCallbackIntent,
sessionEndCallbackIntent);
}
private static java.time.Duration toDuration(j$.time.Duration duration) {
if (duration == null) {
return null;
}
return java.time.Duration.ofSeconds(duration.getSeconds(), duration.getNano());
}
}
| Add conversion for hidden UsageStatsManager.registerAppUsageLimitObserver
PiperOrigin-RevId: 241612554
| src/tools/android/java/com/google/devtools/build/android/desugar/runtime/HiddenConversions.java | Add conversion for hidden UsageStatsManager.registerAppUsageLimitObserver | <ide><path>rc/tools/android/java/com/google/devtools/build/android/desugar/runtime/HiddenConversions.java
<ide> return null;
<ide> }
<ide> return j$.time.LocalDate.of(date.getYear(), date.getMonthValue(), date.getDayOfMonth());
<add> }
<add>
<add> public static void registerAppUsageLimitObserver(
<add> UsageStatsManager receiver,
<add> int observerId,
<add> String[] observedEntities,
<add> j$.time.Duration timeLimit,
<add> j$.time.Duration timeUsed,
<add> PendingIntent callbackIntent) {
<add> receiver.registerAppUsageLimitObserver(
<add> observerId, observedEntities, toDuration(timeLimit), toDuration(timeUsed), callbackIntent);
<ide> }
<ide>
<ide> public static void registerUsageSessionObserver( |
|
Java | bsd-3-clause | e69edc89f680d68b32ff7a57754d7ac85bd703d9 | 0 | raptor-chess/raptor-chess-interface,evilwan/raptor-chess-interface,evilwan/raptor-chess-interface,evilwan/raptor-chess-interface,NightSwimming/Raptor-Chess,NightSwimming/Raptor-Chess,raptor-chess/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,raptor-chess/raptor-chess-interface,NightSwimming/Raptor-Chess,evilwan/raptor-chess-interface,NightSwimming/Raptor-Chess,raptor-chess-interface/raptor-chess-interface,raptor-chess/raptor-chess-interface | package raptor.swt.chess.layout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import raptor.Raptor;
import raptor.pref.PreferenceKeys;
import raptor.swt.SWTUtils;
import raptor.swt.chess.ChessBoard;
import raptor.swt.chess.ChessBoardLayout;
public class TopBottomOrientedLayout extends ChessBoardLayout {
private static final Log LOG = LogFactory
.getLog(TopBottomOrientedLayout.class);
public static final int[] BOARD_WIDTH_MARGIN_PERCENTAGES = { 2, 1 };
public static final int[] TOP_BOTTOM_MARGIN_PERCENTAGES = { 2, 1 };
public static final int NORTH = 0;
public static final int SOUTH = 1;
public static final int EAST = 1;
public static final int WEST = 0;
protected Point boardTopLeft;
protected Rectangle bottomClockRect;
protected Rectangle bottomLagRect;
protected Rectangle bottomNameLabelRect;
protected Point bottomPieceJailTopLeft;
protected ControlListener controlListener;
protected Rectangle currentPremovesLabelRect;
protected Rectangle gameDescriptionLabelRect;
protected boolean hasHeightProblem = false;
protected boolean hasSevereHeightProblem = false;
protected Rectangle openingDescriptionLabelRect;
protected int pieceJailSquareSize;
protected int squareSize;
protected Rectangle statusLabelRect;
protected Rectangle topClockRect;
protected Rectangle topLagRect;
protected Rectangle topNameLabelRect;
protected Point topPieceJailTopLeft;
public TopBottomOrientedLayout(ChessBoard board) {
super(board);
board.getBoardComposite().addControlListener(
controlListener = new ControlListener() {
public void controlMoved(ControlEvent e) {
}
public void controlResized(ControlEvent e) {
setLayoutData();
}
});
}
@Override
public void adjustFontSizes() {
if (LOG.isDebugEnabled()) {
LOG.debug("Adjusting font sizes.");
}
board.getGameDescriptionLabel().setFont(
getFont(PreferenceKeys.BOARD_GAME_DESCRIPTION_FONT));
board.getCurrentPremovesLabel().setFont(
getFont(PreferenceKeys.BOARD_PREMOVES_FONT));
board.getStatusLabel().setFont(
getFont(PreferenceKeys.BOARD_STATUS_FONT));
board.getOpeningDescriptionLabel().setFont(
getFont(PreferenceKeys.BOARD_OPENING_DESC_FONT));
board.getWhiteNameRatingLabel().setFont(
getFont(PreferenceKeys.BOARD_PLAYER_NAME_FONT));
board.getBlackNameRatingLabel().setFont(
getFont(PreferenceKeys.BOARD_PLAYER_NAME_FONT));
board.getWhiteLagLabel()
.setFont(getFont(PreferenceKeys.BOARD_LAG_FONT));
board.getBlackLagLabel()
.setFont(getFont(PreferenceKeys.BOARD_LAG_FONT));
board.getWhiteClockLabel().setFont(
getFont(PreferenceKeys.BOARD_CLOCK_FONT));
board.getBlackClockLabel().setFont(
getFont(PreferenceKeys.BOARD_CLOCK_FONT));
}
@Override
public void dispose() {
super.dispose();
if (!board.isDisposed()) {
board.getBoardComposite().removeControlListener(controlListener);
}
if (LOG.isInfoEnabled()) {
LOG.info("Dispoed TopBottomOrientedLayout");
}
}
@Override
public int getAlignment(Field field) {
switch (field) {
case GAME_DESCRIPTION_LABEL:
return SWT.LEFT;
case CURRENT_PREMOVE_LABEL:
return SWT.LEFT;
case STATUS_LABEL:
return SWT.LEFT;
case OPENING_DESCRIPTION_LABEL:
return SWT.LEFT;
case NAME_RATING_LABEL:
return SWT.LEFT;
case CLOCK_LABEL:
return SWT.RIGHT;
case LAG_LABEL:
return SWT.LEFT;
case UP_TIME_LABEL:
return SWT.LEFT | SWT.BORDER;
default:
return SWT.NONE;
}
}
@Override
public String getName() {
return "Top Bottom Oriented";
}
protected Font getFont(String property) {
return Raptor.getInstance().getPreferences().getFont(property);
}
@Override
protected void layout(Composite composite, boolean flushCache) {
if (LOG.isDebugEnabled()) {
LOG.debug("in layout(" + flushCache + ") " + composite.getSize().x
+ " " + composite.getSize().y);
}
if (flushCache) {
setLayoutData();
}
long startTime = System.currentTimeMillis();
board.getGameDescriptionLabel().setBounds(gameDescriptionLabelRect);
board.getCurrentPremovesLabel().setBounds(currentPremovesLabelRect);
board.getStatusLabel().setBounds(statusLabelRect);
board.getOpeningDescriptionLabel().setBounds(
openingDescriptionLabelRect);
layoutChessBoard(boardTopLeft, squareSize);
board.getWhiteNameRatingLabel().setBounds(
board.isWhiteOnTop() ? topNameLabelRect : bottomNameLabelRect);
board.getWhiteLagLabel().setBounds(
board.isWhiteOnTop() ? topLagRect : bottomLagRect);
board.getWhiteClockLabel().setBounds(
board.isWhiteOnTop() ? topClockRect : bottomClockRect);
board.getBlackNameRatingLabel().setBounds(
board.isWhiteOnTop() ? bottomNameLabelRect : topNameLabelRect);
board.getBlackLagLabel().setBounds(
board.isWhiteOnTop() ? bottomLagRect : topLagRect);
board.getBlackClockLabel().setBounds(
board.isWhiteOnTop() ? bottomClockRect : topClockRect);
if (board.isWhitePieceJailOnTop()) {
board.getPieceJailSquares()[WP].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WN].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y + pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WB].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y + 2 * pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WQ].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WR].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y
+ pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WK].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y + 2
* +pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BP].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BN].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y + pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BB].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y + 2 * pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BQ].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BR].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y
+ pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BK].setBounds(bottomPieceJailTopLeft.x
+ squareSize, bottomPieceJailTopLeft.y + 2
* pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
} else {
board.getPieceJailSquares()[BP].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BN].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y + pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BB].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y + 2 * pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BQ].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BR].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y
+ pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BK].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y + 2
* pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WP].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WN].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y + pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WB].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y + 2 * pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WQ].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WR].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y
+ pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WK].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y + 2
* pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Layout completed in "
+ (System.currentTimeMillis() - startTime));
}
}
protected void setLayoutData() {
if (LOG.isDebugEnabled()) {
LOG.debug("Setting layout data.");
}
int width = board.getBoardComposite().getSize().x;
int height = board.getBoardComposite().getSize().y;
hasHeightProblem = false;
hasSevereHeightProblem = false;
if (width < height) {
height = width;
hasHeightProblem = true;
}
int topBottomNorthMargin = height
* TOP_BOTTOM_MARGIN_PERCENTAGES[NORTH] / 100;
int topBottomSouthMargin = height
* TOP_BOTTOM_MARGIN_PERCENTAGES[SOUTH] / 100;
int topBottomLabelHeight = Math.max(SWTUtils.getHeightInPixels(board
.getWhiteNameRatingLabel().getFont().getFontData()[0]
.getHeight()), SWTUtils.getHeightInPixels(board.getWhiteClockLabel()
.getFont().getFontData()[0].getHeight())) + topBottomNorthMargin + topBottomSouthMargin;
// int bottomLabelHeight = topBottomLabelHeight;
int boardWidthPixelsWest = width * BOARD_WIDTH_MARGIN_PERCENTAGES[WEST]
/ 100;
int boardWidthPixelsEast = width * BOARD_WIDTH_MARGIN_PERCENTAGES[EAST]
/ 100;
squareSize = (height - 2 * topBottomLabelHeight) / 8;
while (width < squareSize * 10 + boardWidthPixelsWest
+ boardWidthPixelsEast) {
squareSize -= 2;
hasSevereHeightProblem = true;
}
pieceJailSquareSize = squareSize;
int topHeight = topBottomLabelHeight;
int bottomControlStartY = topHeight + 8 * squareSize;
boardTopLeft = new Point(boardWidthPixelsWest, topHeight);
int rightControlStartX = boardTopLeft.x + boardWidthPixelsEast + 8
* squareSize;
int rightControlWidth = width - rightControlStartX;
int oneHalfSquareSize = (int) (.5 * squareSize);
gameDescriptionLabelRect = new Rectangle(rightControlStartX, topHeight,
rightControlWidth, oneHalfSquareSize);
currentPremovesLabelRect = new Rectangle(rightControlStartX, topHeight
+ oneHalfSquareSize, rightControlWidth, oneHalfSquareSize);
openingDescriptionLabelRect = new Rectangle(rightControlStartX,
topHeight + 7 * squareSize, rightControlWidth,
oneHalfSquareSize);
statusLabelRect = new Rectangle(rightControlStartX, topHeight + 7
* squareSize + oneHalfSquareSize, rightControlWidth,
oneHalfSquareSize);
topNameLabelRect = new Rectangle(boardWidthPixelsWest,
0, 4 * squareSize, topBottomLabelHeight);
topClockRect = new Rectangle(boardWidthPixelsWest + 4 * squareSize,
0, 4 * squareSize, topBottomLabelHeight);
topLagRect = new Rectangle(rightControlStartX, 0,
rightControlWidth, topBottomLabelHeight);
bottomNameLabelRect = new Rectangle(boardWidthPixelsWest,
bottomControlStartY, 4 * squareSize, topBottomLabelHeight);
bottomClockRect = new Rectangle(boardWidthPixelsWest + 4 * squareSize,
bottomControlStartY, 4 * squareSize, topBottomLabelHeight);
bottomLagRect = new Rectangle(rightControlStartX, bottomControlStartY,
rightControlWidth, topBottomLabelHeight);
topPieceJailTopLeft = new Point(rightControlStartX, topHeight
+ squareSize);
bottomPieceJailTopLeft = new Point(rightControlStartX, topHeight + 4
* squareSize);
}
}
| raptor/src/raptor/swt/chess/layout/TopBottomOrientedLayout.java | package raptor.swt.chess.layout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import raptor.Raptor;
import raptor.pref.PreferenceKeys;
import raptor.swt.SWTUtils;
import raptor.swt.chess.ChessBoard;
import raptor.swt.chess.ChessBoardLayout;
public class TopBottomOrientedLayout extends ChessBoardLayout {
private static final Log LOG = LogFactory
.getLog(TopBottomOrientedLayout.class);
public static final int[] BOARD_WIDTH_MARGIN_PERCENTAGES = { 2, 1 };
public static final int[] TOP_BOTTOM_MARGIN_PERCENTAGES = { 2, 1 };
public static final int NORTH = 0;
public static final int SOUTH = 1;
public static final int EAST = 1;
public static final int WEST = 0;
protected Point boardTopLeft;
protected Rectangle bottomClockRect;
protected Rectangle bottomLagRect;
protected Rectangle bottomNameLabelRect;
protected Point bottomPieceJailTopLeft;
protected ControlListener controlListener;
protected Rectangle currentPremovesLabelRect;
protected Rectangle gameDescriptionLabelRect;
protected boolean hasHeightProblem = false;
protected boolean hasSevereHeightProblem = false;
protected Rectangle openingDescriptionLabelRect;
protected int pieceJailSquareSize;
protected int squareSize;
protected Rectangle statusLabelRect;
protected Rectangle topClockRect;
protected Rectangle topLagRect;
protected Rectangle topNameLabelRect;
protected Point topPieceJailTopLeft;
public TopBottomOrientedLayout(ChessBoard board) {
super(board);
board.getBoardComposite().addControlListener(
controlListener = new ControlListener() {
public void controlMoved(ControlEvent e) {
}
public void controlResized(ControlEvent e) {
setLayoutData();
}
});
}
@Override
public void adjustFontSizes() {
if (LOG.isDebugEnabled()) {
LOG.debug("Adjusting font sizes.");
}
board.getGameDescriptionLabel().setFont(
getFont(PreferenceKeys.BOARD_GAME_DESCRIPTION_FONT));
board.getCurrentPremovesLabel().setFont(
getFont(PreferenceKeys.BOARD_PREMOVES_FONT));
board.getStatusLabel().setFont(
getFont(PreferenceKeys.BOARD_STATUS_FONT));
board.getOpeningDescriptionLabel().setFont(
getFont(PreferenceKeys.BOARD_OPENING_DESC_FONT));
board.getWhiteNameRatingLabel().setFont(
getFont(PreferenceKeys.BOARD_PLAYER_NAME_FONT));
board.getBlackNameRatingLabel().setFont(
getFont(PreferenceKeys.BOARD_PLAYER_NAME_FONT));
board.getWhiteLagLabel()
.setFont(getFont(PreferenceKeys.BOARD_LAG_FONT));
board.getBlackLagLabel()
.setFont(getFont(PreferenceKeys.BOARD_LAG_FONT));
board.getWhiteClockLabel().setFont(
getFont(PreferenceKeys.BOARD_CLOCK_FONT));
board.getBlackClockLabel().setFont(
getFont(PreferenceKeys.BOARD_CLOCK_FONT));
}
@Override
public void dispose() {
super.dispose();
if (!board.isDisposed()) {
board.getBoardComposite().removeControlListener(controlListener);
}
if (LOG.isInfoEnabled()) {
LOG.info("Dispoed TopBottomOrientedLayout");
}
}
@Override
public int getAlignment(Field field) {
switch (field) {
case GAME_DESCRIPTION_LABEL:
return SWT.LEFT;
case CURRENT_PREMOVE_LABEL:
return SWT.LEFT;
case STATUS_LABEL:
return SWT.LEFT;
case OPENING_DESCRIPTION_LABEL:
return SWT.LEFT;
case NAME_RATING_LABEL:
return SWT.LEFT;
case CLOCK_LABEL:
return SWT.RIGHT;
case LAG_LABEL:
return SWT.LEFT;
case UP_TIME_LABEL:
return SWT.LEFT | SWT.BORDER;
default:
return SWT.NONE;
}
}
@Override
public String getName() {
return "Top Bottom Oriented";
}
protected Font getFont(String property) {
return Raptor.getInstance().getPreferences().getFont(property);
}
@Override
protected void layout(Composite composite, boolean flushCache) {
if (LOG.isDebugEnabled()) {
LOG.debug("in layout(" + flushCache + ") " + composite.getSize().x
+ " " + composite.getSize().y);
}
if (flushCache) {
setLayoutData();
}
long startTime = System.currentTimeMillis();
board.getGameDescriptionLabel().setBounds(gameDescriptionLabelRect);
board.getCurrentPremovesLabel().setBounds(currentPremovesLabelRect);
board.getStatusLabel().setBounds(statusLabelRect);
board.getOpeningDescriptionLabel().setBounds(
openingDescriptionLabelRect);
layoutChessBoard(boardTopLeft, squareSize);
board.getWhiteNameRatingLabel().setBounds(
board.isWhiteOnTop() ? topNameLabelRect : bottomNameLabelRect);
board.getWhiteLagLabel().setBounds(
board.isWhiteOnTop() ? topLagRect : bottomLagRect);
board.getWhiteClockLabel().setBounds(
board.isWhiteOnTop() ? topClockRect : bottomClockRect);
board.getBlackNameRatingLabel().setBounds(
board.isWhiteOnTop() ? bottomNameLabelRect : topNameLabelRect);
board.getBlackLagLabel().setBounds(
board.isWhiteOnTop() ? bottomLagRect : topLagRect);
board.getBlackClockLabel().setBounds(
board.isWhiteOnTop() ? bottomClockRect : topClockRect);
if (board.isWhitePieceJailOnTop()) {
board.getPieceJailSquares()[WP].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WN].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y + pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WB].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y + 2 * pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WQ].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WR].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y
+ pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WK].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y + 2
* +pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BP].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BN].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y + pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BB].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y + 2 * pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BQ].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BR].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y
+ pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BK].setBounds(bottomPieceJailTopLeft.x
+ squareSize, bottomPieceJailTopLeft.y + 2
* pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
} else {
board.getPieceJailSquares()[BP].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BN].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y + pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BB].setBounds(topPieceJailTopLeft.x,
topPieceJailTopLeft.y + 2 * pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BQ].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[BR].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y
+ pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[BK].setBounds(topPieceJailTopLeft.x
+ pieceJailSquareSize, topPieceJailTopLeft.y + 2
* pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WP].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WN].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y + pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WB].setBounds(bottomPieceJailTopLeft.x,
bottomPieceJailTopLeft.y + 2 * pieceJailSquareSize,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WQ].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y,
pieceJailSquareSize, pieceJailSquareSize);
board.getPieceJailSquares()[WR].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y
+ pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
board.getPieceJailSquares()[WK].setBounds(bottomPieceJailTopLeft.x
+ pieceJailSquareSize, bottomPieceJailTopLeft.y + 2
* pieceJailSquareSize, pieceJailSquareSize,
pieceJailSquareSize);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Layout completed in "
+ (System.currentTimeMillis() - startTime));
}
}
protected void setLayoutData() {
if (LOG.isDebugEnabled()) {
LOG.debug("Setting layout data.");
}
int width = board.getBoardComposite().getSize().x;
int height = board.getBoardComposite().getSize().y;
hasHeightProblem = false;
hasSevereHeightProblem = false;
if (width < height) {
height = width;
hasHeightProblem = true;
}
int topBottomNorthMargin = height
* TOP_BOTTOM_MARGIN_PERCENTAGES[NORTH] / 100;
int topBottomSouthMargin = height
* TOP_BOTTOM_MARGIN_PERCENTAGES[SOUTH] / 100;
int topBottomLabelHeight = Math.max(SWTUtils.getHeightInPixels(board
.getWhiteNameRatingLabel().getFont().getFontData()[0]
.getHeight()), SWTUtils.getHeightInPixels(board.getWhiteClockLabel()
.getFont().getFontData()[0].getHeight()));
int bottomLabelHeight = topBottomLabelHeight;
int boardWidthPixelsWest = width * BOARD_WIDTH_MARGIN_PERCENTAGES[WEST]
/ 100;
int boardWidthPixelsEast = width * BOARD_WIDTH_MARGIN_PERCENTAGES[EAST]
/ 100;
squareSize = (height - 2 * topBottomNorthMargin - 2
* topBottomSouthMargin - 2 * topBottomLabelHeight) / 8;
while (width < squareSize * 10 + boardWidthPixelsWest
+ boardWidthPixelsEast) {
squareSize -= 2;
hasSevereHeightProblem = true;
}
pieceJailSquareSize = squareSize;
int topHeight = topBottomNorthMargin + topBottomSouthMargin
+ topBottomLabelHeight;
int bottomControlStartY = topHeight + 8 * squareSize;
boardTopLeft = new Point(boardWidthPixelsWest, topHeight);
int rightControlStartX = boardTopLeft.x + boardWidthPixelsEast + 8
* squareSize;
int rightControlWidth = width - rightControlStartX;
int oneHalfSquareSize = (int) (.5 * squareSize);
gameDescriptionLabelRect = new Rectangle(rightControlStartX, topHeight,
rightControlWidth, oneHalfSquareSize);
currentPremovesLabelRect = new Rectangle(rightControlStartX, topHeight
+ oneHalfSquareSize, rightControlWidth, oneHalfSquareSize);
openingDescriptionLabelRect = new Rectangle(rightControlStartX,
topHeight + 7 * squareSize, rightControlWidth,
oneHalfSquareSize);
statusLabelRect = new Rectangle(rightControlStartX, topHeight + 7
* squareSize + oneHalfSquareSize, rightControlWidth,
oneHalfSquareSize);
topNameLabelRect = new Rectangle(boardWidthPixelsWest,
0, 4 * squareSize, topBottomLabelHeight);
topClockRect = new Rectangle(boardWidthPixelsWest + 4 * squareSize,
0, 4 * squareSize, topBottomLabelHeight);
topLagRect = new Rectangle(rightControlStartX, 0,
rightControlWidth, topBottomLabelHeight);
bottomNameLabelRect = new Rectangle(boardWidthPixelsWest,
bottomControlStartY, 4 * squareSize, bottomLabelHeight);
bottomClockRect = new Rectangle(boardWidthPixelsWest + 4 * squareSize,
bottomControlStartY, 4 * squareSize, bottomLabelHeight);
bottomLagRect = new Rectangle(rightControlStartX, bottomControlStartY,
rightControlWidth, topBottomLabelHeight);
topPieceJailTopLeft = new Point(rightControlStartX, topHeight
+ squareSize);
bottomPieceJailTopLeft = new Point(rightControlStartX, topHeight + 4
* squareSize);
}
}
| TopBottom layout changes
| raptor/src/raptor/swt/chess/layout/TopBottomOrientedLayout.java | TopBottom layout changes | <ide><path>aptor/src/raptor/swt/chess/layout/TopBottomOrientedLayout.java
<ide> int topBottomLabelHeight = Math.max(SWTUtils.getHeightInPixels(board
<ide> .getWhiteNameRatingLabel().getFont().getFontData()[0]
<ide> .getHeight()), SWTUtils.getHeightInPixels(board.getWhiteClockLabel()
<del> .getFont().getFontData()[0].getHeight()));
<del>
<del> int bottomLabelHeight = topBottomLabelHeight;
<add> .getFont().getFontData()[0].getHeight())) + topBottomNorthMargin + topBottomSouthMargin;
<add>
<add>// int bottomLabelHeight = topBottomLabelHeight;
<ide>
<ide> int boardWidthPixelsWest = width * BOARD_WIDTH_MARGIN_PERCENTAGES[WEST]
<ide> / 100;
<ide> int boardWidthPixelsEast = width * BOARD_WIDTH_MARGIN_PERCENTAGES[EAST]
<ide> / 100;
<ide>
<del> squareSize = (height - 2 * topBottomNorthMargin - 2
<del> * topBottomSouthMargin - 2 * topBottomLabelHeight) / 8;
<add> squareSize = (height - 2 * topBottomLabelHeight) / 8;
<ide>
<ide> while (width < squareSize * 10 + boardWidthPixelsWest
<ide> + boardWidthPixelsEast) {
<ide>
<ide> pieceJailSquareSize = squareSize;
<ide>
<del> int topHeight = topBottomNorthMargin + topBottomSouthMargin
<del> + topBottomLabelHeight;
<add> int topHeight = topBottomLabelHeight;
<ide>
<ide> int bottomControlStartY = topHeight + 8 * squareSize;
<ide>
<ide> rightControlWidth, topBottomLabelHeight);
<ide>
<ide> bottomNameLabelRect = new Rectangle(boardWidthPixelsWest,
<del> bottomControlStartY, 4 * squareSize, bottomLabelHeight);
<add> bottomControlStartY, 4 * squareSize, topBottomLabelHeight);
<ide> bottomClockRect = new Rectangle(boardWidthPixelsWest + 4 * squareSize,
<del> bottomControlStartY, 4 * squareSize, bottomLabelHeight);
<add> bottomControlStartY, 4 * squareSize, topBottomLabelHeight);
<ide> bottomLagRect = new Rectangle(rightControlStartX, bottomControlStartY,
<ide> rightControlWidth, topBottomLabelHeight);
<ide> |
|
Java | apache-2.0 | 12c26d63d52824966c73555818d1ba7718319ef4 | 0 | hekate-io/hekate | /*
* Copyright 2019 The Hekate Project
*
* The Hekate Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.hekate;
import io.hekate.codec.CodecFactory;
import io.hekate.codec.JdkCodecFactory;
import io.hekate.codec.fst.FstCodecFactory;
import io.hekate.codec.kryo.KryoCodecFactory;
import java.util.Collection;
import java.util.stream.Stream;
import org.junit.runners.Parameterized.Parameters;
public abstract class HekateNodeMultiCodecTestBase extends HekateNodeParamTestBase {
public static class MultiCodecTestContext extends HekateTestContext {
private final CodecFactory<Object> codecFactory;
public MultiCodecTestContext(HekateTestContext src, CodecFactory<Object> codecFactory) {
super(src);
this.codecFactory = codecFactory;
}
public CodecFactory<Object> codecFactory() {
return codecFactory;
}
}
private final MultiCodecTestContext ctx;
public HekateNodeMultiCodecTestBase(MultiCodecTestContext ctx) {
super(ctx);
this.ctx = ctx;
}
@Parameters(name = "{index}: {0}")
public static Collection<MultiCodecTestContext> getCodecTestContexts() {
return mapTestContext(p -> Stream.of(
new MultiCodecTestContext(p, new KryoCodecFactory<>()),
new MultiCodecTestContext(p, new FstCodecFactory<>()),
new MultiCodecTestContext(p, new JdkCodecFactory<>())
));
}
@Override
protected CodecFactory<Object> defaultCodec() {
return ctx.codecFactory();
}
}
| hekate-core/src/test/java/io/hekate/HekateNodeMultiCodecTestBase.java | /*
* Copyright 2019 The Hekate Project
*
* The Hekate Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.hekate;
import io.hekate.codec.CodecFactory;
import io.hekate.codec.JdkCodecFactory;
import io.hekate.codec.fst.FstCodecFactory;
import io.hekate.codec.kryo.KryoCodecFactory;
import java.util.Collection;
import java.util.stream.Stream;
import org.junit.runners.Parameterized.Parameters;
public abstract class HekateNodeMultiCodecTestBase extends HekateNodeParamTestBase {
public static class MultiCodecTestContext extends HekateTestContext {
private final CodecFactory<Object> codecFactory;
public MultiCodecTestContext(HekateTestContext src, CodecFactory<Object> codecFactory) {
super(src);
this.codecFactory = codecFactory;
}
public CodecFactory<Object> codecFactory() {
return codecFactory;
}
}
private final MultiCodecTestContext ctx;
public HekateNodeMultiCodecTestBase(MultiCodecTestContext ctx) {
super(ctx);
this.ctx = ctx;
}
@Parameters(name = "{index}: {0}")
public static Collection<MultiCodecTestContext> getLockAsyncTestContexts() {
return mapTestContext(p -> Stream.of(
new MultiCodecTestContext(p, new KryoCodecFactory<>()),
new MultiCodecTestContext(p, new FstCodecFactory<>()),
new MultiCodecTestContext(p, new JdkCodecFactory<>())
));
}
@Override
protected CodecFactory<Object> defaultCodec() {
return ctx.codecFactory();
}
}
| Fix typo in test method name [ci skip]
| hekate-core/src/test/java/io/hekate/HekateNodeMultiCodecTestBase.java | Fix typo in test method name [ci skip] | <ide><path>ekate-core/src/test/java/io/hekate/HekateNodeMultiCodecTestBase.java
<ide> }
<ide>
<ide> @Parameters(name = "{index}: {0}")
<del> public static Collection<MultiCodecTestContext> getLockAsyncTestContexts() {
<add> public static Collection<MultiCodecTestContext> getCodecTestContexts() {
<ide> return mapTestContext(p -> Stream.of(
<ide> new MultiCodecTestContext(p, new KryoCodecFactory<>()),
<ide> new MultiCodecTestContext(p, new FstCodecFactory<>()), |
|
Java | mit | 4eb9a60426a51d260780a5549984d69f0a12bfea | 0 | algolia/algoliasearch-client-java,algoliareadmebot/algoliasearch-client-java,algolia/algoliasearch-client-java,algoliareadmebot/algoliasearch-client-java | package com.algolia.search.saas;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.SystemDefaultCredentialsProvider;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/*
* Copyright (c) 2015 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Entry point in the Java API.
* You should instantiate a Client object with your ApplicationID, ApiKey and Hosts
* to start using Algolia Search API
*/
public class APIClient {
private int httpSocketTimeoutMS = 20000;
private int httpConnectTimeoutMS = 2000;
private int httpSearchTimeoutMS = 2000;
private final static String version;
private final static String fallbackDomain;
static {
String tmp = "N/A";
try {
InputStream versionStream = APIClient.class.getResourceAsStream("/version.properties");
if (versionStream != null) {
BufferedReader versionReader = new BufferedReader(new InputStreamReader(versionStream));
tmp = versionReader.readLine();
versionReader.close();
}
} catch (IOException e) {
// not fatal
}
version = tmp;
// fallback domain should be algolia.net if Java <= 1.6 because no SNI support
{
String version = System.getProperty("java.version");
int pos = version.indexOf('.');
pos = version.indexOf('.', pos + 1);
fallbackDomain = Double.parseDouble(version.substring(0, pos)) <= 1.6 ? "algolia.net" : "algolianet.com";
}
}
private final String applicationID;
private final String apiKey;
private final List<String> buildHostsArray;
private final List<String> queryHostsArray;
private final HttpClient httpClient;
private String forwardRateLimitAPIKey;
private String forwardEndUserIP;
private String forwardAdminAPIKey;
private HashMap<String, String> headers;
private final boolean verbose;
private String userAgent;
/**
* Algolia Search initialization
*
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
*/
public APIClient(String applicationID, String apiKey) {
this(applicationID, apiKey, Arrays.asList(applicationID + "-1." + fallbackDomain,
applicationID + "-2." + fallbackDomain,
applicationID + "-3." + fallbackDomain));
this.buildHostsArray.add(0, applicationID + ".algolia.net");
this.queryHostsArray.add(0, applicationID + "-dsn.algolia.net");
}
/**
* Algolia Search initialization
*
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
* @param hostsArray the list of hosts that you have received for the service
*/
public APIClient(String applicationID, String apiKey, List<String> hostsArray) {
this(applicationID, apiKey, hostsArray, hostsArray);
}
/**
* Algolia Search initialization
*
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
* @param buildHostsArray the list of hosts that you have received for the service
* @param queryHostsArray the list of hosts that you have received for the service
*/
public APIClient(String applicationID, String apiKey, List<String> buildHostsArray, List<String> queryHostsArray) {
userAgent = "Algolia for Java (" + version + "); JVM (" + System.getProperty("java.version") + ")";
verbose = System.getenv("VERBOSE") != null;
forwardRateLimitAPIKey = forwardAdminAPIKey = forwardEndUserIP = null;
if (applicationID == null || applicationID.length() == 0) {
throw new RuntimeException("AlgoliaSearch requires an applicationID.");
}
this.applicationID = applicationID;
if (apiKey == null || apiKey.length() == 0) {
throw new RuntimeException("AlgoliaSearch requires an apiKey.");
}
this.apiKey = apiKey;
if (buildHostsArray == null || buildHostsArray.size() == 0 || queryHostsArray == null || queryHostsArray.size() == 0) {
throw new RuntimeException("AlgoliaSearch requires a list of hostnames.");
}
this.buildHostsArray = new ArrayList<String>(buildHostsArray);
this.queryHostsArray = new ArrayList<String>(queryHostsArray);
httpClient = HttpClientBuilder.create().disableAutomaticRetries().useSystemProperties().build();
headers = new HashMap<String, String>();
}
/**
* Allow to modify the user-agent in order to add the user agent of the integration
*/
public void setUserAgent(String agent, String agentVersion) {
userAgent = String.format("Algolia for Java (%s); JVM (%s); %s (%s)", version, System.getProperty("java.version"), agent, agentVersion);
}
/**
* Allow to use IP rate limit when you have a proxy between end-user and Algolia.
* This option will set the X-Forwarded-For HTTP header with the client IP and the X-Forwarded-API-Key with the API Key having rate limits.
*
* @param adminAPIKey the admin API Key you can find in your dashboard
* @param endUserIP the end user IP (you can use both IPV4 or IPV6 syntax)
* @param rateLimitAPIKey the API key on which you have a rate limit
*/
public void enableRateLimitForward(String adminAPIKey, String endUserIP, String rateLimitAPIKey) {
this.forwardAdminAPIKey = adminAPIKey;
this.forwardEndUserIP = endUserIP;
this.forwardRateLimitAPIKey = rateLimitAPIKey;
}
/**
* Disable IP rate limit enabled with enableRateLimitForward() function
*/
public void disableRateLimitForward() {
forwardAdminAPIKey = forwardEndUserIP = forwardRateLimitAPIKey = null;
}
/**
* Allow to set custom headers
*/
public void setExtraHeader(String key, String value) {
headers.put(key, value);
}
/**
* Allow to set the timeout
*
* @param connectTimeout connection timeout in MS
* @param readTimeout socket timeout in MS
*/
public void setTimeout(int connectTimeout, int readTimeout) {
httpSocketTimeoutMS = readTimeout;
httpConnectTimeoutMS = connectTimeout;
}
/**
* List all existing indexes
* return an JSON Object in the form:
* { "items": [ {"name": "contacts", "createdAt": "2013-01-18T15:33:13.556Z"},
* {"name": "notes", "createdAt": "2013-01-18T15:33:13.556Z"}]}
*/
public JSONObject listIndexes() throws AlgoliaException {
return getRequest("/1/indexes/", false);
}
/**
* Delete an index
*
* @param indexName the name of index to delete
* return an object containing a "deletedAt" attribute
*/
public JSONObject deleteIndex(String indexName) throws AlgoliaException {
try {
return deleteRequest("/1/indexes/" + URLEncoder.encode(indexName, "UTF-8"), true);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
}
/**
* Move an existing index.
*
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
*/
public JSONObject moveIndex(String srcIndexName, String dstIndexName) throws AlgoliaException {
return operationOnIndex("move", srcIndexName, dstIndexName);
}
/**
* Copy an existing index.
*
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
*/
public JSONObject copyIndex(String srcIndexName, String dstIndexName) throws AlgoliaException {
return operationOnIndex("copy", srcIndexName, dstIndexName);
}
private JSONObject operationOnIndex(String operation, String srcIndexName, String dstIndexName) throws AlgoliaException {
try {
JSONObject content = new JSONObject();
content.put("operation", operation);
content.put("destination", dstIndexName);
return postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString(), true, false);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
} catch (JSONException e) {
throw new AlgoliaException(e.getMessage()); // $COVERAGE-IGNORE$
}
}
public enum LogType {
/// all query logs
LOG_QUERY,
/// all build logs
LOG_BUILD,
/// all error logs
LOG_ERROR,
/// all logs
LOG_ALL
}
/**
* Return 10 last log entries.
*/
public JSONObject getLogs() throws AlgoliaException {
return getRequest("/1/logs", false);
}
/**
* Return last logs entries.
*
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
*/
public JSONObject getLogs(int offset, int length) throws AlgoliaException {
return getLogs(offset, length, LogType.LOG_ALL);
}
/**
* Return last logs entries.
*
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
* @param onlyErrors Retrieve only logs with an httpCode different than 200 and 201
*/
public JSONObject getLogs(int offset, int length, boolean onlyErrors) throws AlgoliaException {
return getLogs(offset, length, onlyErrors ? LogType.LOG_ERROR : LogType.LOG_ALL);
}
/**
* Return last logs entries.
*
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
* @param logType Specify the type of log to retrieve
*/
public JSONObject getLogs(int offset, int length, LogType logType) throws AlgoliaException {
String type = null;
switch (logType) {
case LOG_BUILD:
type = "build";
break;
case LOG_QUERY:
type = "query";
break;
case LOG_ERROR:
type = "error";
break;
case LOG_ALL:
type = "all";
break;
}
return getRequest("/1/logs?offset=" + offset + "&length=" + length + "&type=" + type, false);
}
/**
* Get the index object initialized (no server call needed for initialization)
*
* @param indexName the name of index
*/
public Index initIndex(String indexName) {
return new Index(this, indexName);
}
/**
* List all existing user keys with their associated ACLs
*/
public JSONObject listUserKeys() throws AlgoliaException {
return getRequest("/1/keys", false);
}
/**
* Get ACL of a user key
*/
public JSONObject getUserKeyACL(String key) throws AlgoliaException {
return getRequest("/1/keys/" + key, false);
}
/**
* Delete an existing user key
*/
public JSONObject deleteUserKey(String key) throws AlgoliaException {
return deleteRequest("/1/keys/" + key, true);
}
/**
* Create a new user key
*
* @param params the list of parameters for this key. Defined by a JSONObject that
* can contains the following values:
* - acl: array of string
* - indices: array of string
* - validity: int
* - referers: array of string
* - description: string
* - maxHitsPerQuery: integer
* - queryParameters: string
* - maxQueriesPerIPPerHour: integer
*/
public JSONObject addUserKey(JSONObject params) throws AlgoliaException {
return postRequest("/1/keys", params.toString(), true, false);
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
*/
public JSONObject addUserKey(List<String> acls) throws AlgoliaException {
return addUserKey(acls, 0, 0, 0, null);
}
/**
* Update a user key
*
* @param params the list of parameters for this key. Defined by a JSONObject that
* can contains the following values:
* - acl: array of string
* - indices: array of string
* - validity: int
* - referers: array of string
* - description: string
* - maxHitsPerQuery: integer
* - queryParameters: string
* - maxQueriesPerIPPerHour: integer
*/
public JSONObject updateUserKey(String key, JSONObject params) throws AlgoliaException {
return putRequest("/1/keys/" + key, params.toString(), true);
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
*/
public JSONObject updateUserKey(String key, List<String> acls) throws AlgoliaException {
return updateUserKey(key, acls, 0, 0, 0, null);
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
*/
public JSONObject addUserKey(List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery) throws AlgoliaException {
return addUserKey(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, null);
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
*/
public JSONObject updateUserKey(String key, List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery) throws AlgoliaException {
return updateUserKey(key, acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, null);
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
* @param indexes the list of targeted indexes
*/
public JSONObject addUserKey(List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) throws AlgoliaException {
JSONObject jsonObject = generateUserKeyJson(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, indexes);
return addUserKey(jsonObject);
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
* @param indexes the list of targeted indexes
*/
public JSONObject updateUserKey(String key, List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) throws AlgoliaException {
JSONObject jsonObject = generateUserKeyJson(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, indexes);
return updateUserKey(key, jsonObject);
}
private JSONObject generateUserKeyJson(List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) {
JSONArray array = new JSONArray(acls);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("acl", array);
jsonObject.put("validity", validity);
jsonObject.put("maxQueriesPerIPPerHour", maxQueriesPerIPPerHour);
jsonObject.put("maxHitsPerQuery", maxHitsPerQuery);
if (indexes != null) {
jsonObject.put("indexes", new JSONArray(indexes));
}
} catch (JSONException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
return jsonObject;
}
/**
* Generate a secured and public API Key from a list of tagFilters and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param tagFilters the list of tags applied to the query (used as security)
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @deprecated Use `generateSecuredApiKey(String privateApiKey, Query query)` version
*/
@Deprecated
public String generateSecuredApiKey(String privateApiKey, String tagFilters) throws NoSuchAlgorithmException, InvalidKeyException {
if (!tagFilters.contains("="))
return generateSecuredApiKey(privateApiKey, new Query().setTagFilters(tagFilters), null);
else {
return Base64.encodeBase64String(String.format("%s%s", hmac(privateApiKey, tagFilters), tagFilters).getBytes(Charset.forName("UTF8")));
}
}
/**
* Generate a secured and public API Key from a query and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param query contains the parameter applied to the query (used as security)
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public String generateSecuredApiKey(String privateApiKey, Query query) throws NoSuchAlgorithmException, InvalidKeyException {
return generateSecuredApiKey(privateApiKey, query, null);
}
/**
* Generate a secured and public API Key from a list of tagFilters and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param tagFilters the list of tags applied to the query (used as security)
* @param userToken an optional token identifying the current user
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws AlgoliaException
* @deprecated Use `generateSecuredApiKey(String privateApiKey, Query query, String userToken)` version
*/
@Deprecated
public String generateSecuredApiKey(String privateApiKey, String tagFilters, String userToken) throws NoSuchAlgorithmException, InvalidKeyException, AlgoliaException {
if (!tagFilters.contains("="))
return generateSecuredApiKey(privateApiKey, new Query().setTagFilters(tagFilters), userToken);
else {
if (userToken != null && userToken.length() > 0) {
try {
tagFilters = String.format("%s%s%s", tagFilters, "&userToken=", URLEncoder.encode(userToken, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AlgoliaException(e.getMessage());
}
}
return Base64.encodeBase64String(String.format("%s%s", hmac(privateApiKey, tagFilters), tagFilters).getBytes(Charset.forName("UTF8")));
}
}
/**
* Generate a secured and public API Key from a query and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param query contains the parameter applied to the query (used as security)
* @param userToken an optional token identifying the current user
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public String generateSecuredApiKey(String privateApiKey, Query query, String userToken) throws NoSuchAlgorithmException, InvalidKeyException {
if (userToken != null && userToken.length() > 0) {
query.setUserToken(userToken);
}
String queryStr = query.getQueryString();
String key = hmac(privateApiKey, queryStr);
return Base64.encodeBase64String(String.format("%s%s", key, queryStr).getBytes(Charset.forName("UTF8")));
}
static String hmac(String key, String msg) {
Mac hmac;
try {
hmac = Mac.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException e) {
throw new Error(e);
}
try {
hmac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
} catch (InvalidKeyException e) {
throw new Error(e);
}
byte[] rawHmac = hmac.doFinal(msg.getBytes());
byte[] hexBytes = new Hex().encode(rawHmac);
return new String(hexBytes);
}
private enum Method {
GET, POST, PUT, DELETE
}
protected JSONObject getRequest(String url, boolean search) throws AlgoliaException {
return _request(Method.GET, url, null, false, search);
}
protected JSONObject deleteRequest(String url, boolean build) throws AlgoliaException {
return _request(Method.DELETE, url, null, build, false);
}
protected JSONObject postRequest(String url, String obj, boolean build, boolean search) throws AlgoliaException {
return _request(Method.POST, url, obj, build, search);
}
protected JSONObject putRequest(String url, String obj, boolean build) throws AlgoliaException {
return _request(Method.PUT, url, obj, build, false);
}
private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json, List<AlgoliaInnerException> errors, boolean searchTimeout) throws AlgoliaException {
req.reset();
// set URL
try {
req.setURI(new URI("https://" + host + url));
} catch (URISyntaxException e) {
// never reached
throw new IllegalStateException(e);
}
// set auth headers
req.setHeader("Accept-Encoding", "gzip");
req.setHeader("X-Algolia-Application-Id", this.applicationID);
if (forwardAdminAPIKey == null) {
req.setHeader("X-Algolia-API-Key", this.apiKey);
} else {
req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey);
req.setHeader("X-Forwarded-For", this.forwardEndUserIP);
req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey);
}
for (Entry<String, String> entry : headers.entrySet()) {
req.setHeader(entry.getKey(), entry.getValue());
}
// set user agent
req.setHeader("User-Agent", userAgent);
// set JSON entity
if (json != null) {
if (!(req instanceof HttpEntityEnclosingRequestBase)) {
throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity");
}
req.setHeader("Content-type", "application/json");
try {
StringEntity se = new StringEntity(json, "UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
((HttpEntityEnclosingRequestBase) req).setEntity(se);
} catch (Exception e) {
throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$
}
}
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(searchTimeout ? httpSearchTimeoutMS : httpSocketTimeoutMS)
.setConnectTimeout(httpConnectTimeoutMS)
.setConnectionRequestTimeout(httpConnectTimeoutMS)
.build();
req.setConfig(config);
HttpResponse response;
try {
response = httpClient.execute(req);
} catch (IOException e) {
// on error continue on the next host
if (verbose) {
System.out.println(String.format("%s: %s=%s", host, e.getClass().getName(), e.getMessage()));
}
errors.add(new AlgoliaInnerException(host, e));
return null;
}
try {
int code = response.getStatusLine().getStatusCode();
if (code / 100 == 4) {
String message = "";
try {
message = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (code == 400) {
throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request");
} else if (code == 403) {
throw new AlgoliaException(code, message.length() > 0 ? message : "Invalid Application-ID or API-Key");
} else if (code == 404) {
throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist");
} else {
throw new AlgoliaException(code, message.length() > 0 ? message : "Error");
}
}
if (code / 100 != 2) {
try {
if (verbose) {
System.out.println(String.format("%s: %s", host, EntityUtils.toString(response.getEntity())));
}
errors.add(new AlgoliaInnerException(host, EntityUtils.toString(response.getEntity())));
} catch (IOException e) {
if (verbose) {
System.out.println(String.format("%s: %s", host, String.valueOf(code)));
}
errors.add(new AlgoliaInnerException(host, e));
}
// KO, continue
return null;
}
try {
InputStream istream = response.getEntity().getContent();
String encoding = response.getEntity().getContentEncoding() != null ? response.getEntity().getContentEncoding().getValue() : null;
if (encoding != null && encoding.contains("gzip")) {
istream = new GZIPInputStream(istream);
}
InputStreamReader is = new InputStreamReader(istream, "UTF-8");
StringBuilder jsonRaw = new StringBuilder();
char[] buffer = new char[4096];
int read;
while ((read = is.read(buffer)) > 0) {
jsonRaw.append(buffer, 0, read);
}
is.close();
return new JSONObject(jsonRaw.toString());
} catch (IOException e) {
if (verbose) {
System.out.println(String.format("%s: %s=%s", host, e.getClass().getName(), e.getMessage()));
}
errors.add(new AlgoliaInnerException(host, e));
return null;
} catch (JSONException e) {
throw new AlgoliaException("JSON decode error:" + e.getMessage());
}
} finally {
req.releaseConnection();
}
}
private JSONObject _request(Method m, String url, String json, boolean build, boolean search) throws AlgoliaException {
HttpRequestBase req;
switch (m) {
case DELETE:
req = new HttpDelete();
break;
case GET:
req = new HttpGet();
break;
case POST:
req = new HttpPost();
break;
case PUT:
req = new HttpPut();
break;
default:
throw new IllegalArgumentException("Method " + m + " is not supported");
}
List<AlgoliaInnerException> errors = new ArrayList<AlgoliaInnerException>();
List<String> hosts = build ? this.buildHostsArray : this.queryHostsArray;
// for each host
for (String host : hosts) {
JSONObject res = _requestByHost(req, host, url, json, errors, search);
if (res != null) {
return res;
}
}
throw AlgoliaException.from("Hosts unreachable", errors);
}
public static class IndexQuery {
private String index;
private Query query;
public IndexQuery(String index, Query q) {
this.index = index;
this.query = q;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
/**
* This method allows to query multiple indexes with one API call
*/
public JSONObject multipleQueries(List<IndexQuery> queries) throws AlgoliaException {
return multipleQueries(queries, "none");
}
public JSONObject multipleQueries(List<IndexQuery> queries, String strategy) throws AlgoliaException {
try {
JSONArray requests = new JSONArray();
for (IndexQuery indexQuery : queries) {
String paramsString = indexQuery.getQuery().getQueryString();
requests.put(new JSONObject().put("indexName", indexQuery.getIndex()).put("params", paramsString));
}
JSONObject body = new JSONObject().put("requests", requests);
return postRequest("/1/indexes/*/queries?strategy=" + strategy, body.toString(), false, true);
} catch (JSONException e) {
new AlgoliaException(e);
}
return null;
}
/**
* Custom batch
*
* @param actions the array of actions
* @throws AlgoliaException
*/
public JSONObject batch(JSONArray actions) throws AlgoliaException {
return postBatch(actions);
}
/**
* Custom batch
*
* @param actions the array of actions
* @throws AlgoliaException
*/
public JSONObject batch(List<JSONObject> actions) throws AlgoliaException {
return postBatch(actions);
}
private JSONObject postBatch(Object actions) throws AlgoliaException {
try {
JSONObject content = new JSONObject();
content.put("requests", actions);
return postRequest("/1/indexes/*/batch", content.toString(), true, false);
} catch (JSONException e) {
throw new AlgoliaException(e.getMessage());
}
}
}
| src/main/java/com/algolia/search/saas/APIClient.java | package com.algolia.search.saas;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/*
* Copyright (c) 2015 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Entry point in the Java API.
* You should instantiate a Client object with your ApplicationID, ApiKey and Hosts
* to start using Algolia Search API
*/
public class APIClient {
private int httpSocketTimeoutMS = 20000;
private int httpConnectTimeoutMS = 2000;
private int httpSearchTimeoutMS = 2000;
private final static String version;
private final static String fallbackDomain;
static {
String tmp = "N/A";
try {
InputStream versionStream = APIClient.class.getResourceAsStream("/version.properties");
if (versionStream != null) {
BufferedReader versionReader = new BufferedReader(new InputStreamReader(versionStream));
tmp = versionReader.readLine();
versionReader.close();
}
} catch (IOException e) {
// not fatal
}
version = tmp;
// fallback domain should be algolia.net if Java <= 1.6 because no SNI support
{
String version = System.getProperty("java.version");
int pos = version.indexOf('.');
pos = version.indexOf('.', pos + 1);
fallbackDomain = Double.parseDouble(version.substring(0, pos)) <= 1.6 ? "algolia.net" : "algolianet.com";
}
}
private final String applicationID;
private final String apiKey;
private final List<String> buildHostsArray;
private final List<String> queryHostsArray;
private final HttpClient httpClient;
private String forwardRateLimitAPIKey;
private String forwardEndUserIP;
private String forwardAdminAPIKey;
private HashMap<String, String> headers;
private final boolean verbose;
private String userAgent;
/**
* Algolia Search initialization
*
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
*/
public APIClient(String applicationID, String apiKey) {
this(applicationID, apiKey, Arrays.asList(applicationID + "-1." + fallbackDomain,
applicationID + "-2." + fallbackDomain,
applicationID + "-3." + fallbackDomain));
this.buildHostsArray.add(0, applicationID + ".algolia.net");
this.queryHostsArray.add(0, applicationID + "-dsn.algolia.net");
}
/**
* Algolia Search initialization
*
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
* @param hostsArray the list of hosts that you have received for the service
*/
public APIClient(String applicationID, String apiKey, List<String> hostsArray) {
this(applicationID, apiKey, hostsArray, hostsArray);
}
/**
* Algolia Search initialization
*
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
* @param buildHostsArray the list of hosts that you have received for the service
* @param queryHostsArray the list of hosts that you have received for the service
*/
public APIClient(String applicationID, String apiKey, List<String> buildHostsArray, List<String> queryHostsArray) {
userAgent = "Algolia for Java " + version;
verbose = System.getenv("VERBOSE") != null;
forwardRateLimitAPIKey = forwardAdminAPIKey = forwardEndUserIP = null;
if (applicationID == null || applicationID.length() == 0) {
throw new RuntimeException("AlgoliaSearch requires an applicationID.");
}
this.applicationID = applicationID;
if (apiKey == null || apiKey.length() == 0) {
throw new RuntimeException("AlgoliaSearch requires an apiKey.");
}
this.apiKey = apiKey;
if (buildHostsArray == null || buildHostsArray.size() == 0 || queryHostsArray == null || queryHostsArray.size() == 0) {
throw new RuntimeException("AlgoliaSearch requires a list of hostnames.");
}
this.buildHostsArray = new ArrayList<String>(buildHostsArray);
this.queryHostsArray = new ArrayList<String>(queryHostsArray);
httpClient = HttpClientBuilder.create().disableAutomaticRetries().useSystemProperties().build();
headers = new HashMap<String, String>();
}
/**
* Allow to modify the user-agent in order to add the user agent of the integration
*/
public void setUserAgent(String agent, String agentVersion) {
userAgent = String.format("Algolia for Java %s %s (%s)", version, agent, agentVersion);
}
/**
* Allow to use IP rate limit when you have a proxy between end-user and Algolia.
* This option will set the X-Forwarded-For HTTP header with the client IP and the X-Forwarded-API-Key with the API Key having rate limits.
*
* @param adminAPIKey the admin API Key you can find in your dashboard
* @param endUserIP the end user IP (you can use both IPV4 or IPV6 syntax)
* @param rateLimitAPIKey the API key on which you have a rate limit
*/
public void enableRateLimitForward(String adminAPIKey, String endUserIP, String rateLimitAPIKey) {
this.forwardAdminAPIKey = adminAPIKey;
this.forwardEndUserIP = endUserIP;
this.forwardRateLimitAPIKey = rateLimitAPIKey;
}
/**
* Disable IP rate limit enabled with enableRateLimitForward() function
*/
public void disableRateLimitForward() {
forwardAdminAPIKey = forwardEndUserIP = forwardRateLimitAPIKey = null;
}
/**
* Allow to set custom headers
*/
public void setExtraHeader(String key, String value) {
headers.put(key, value);
}
/**
* Allow to set the timeout
*
* @param connectTimeout connection timeout in MS
* @param readTimeout socket timeout in MS
*/
public void setTimeout(int connectTimeout, int readTimeout) {
httpSocketTimeoutMS = readTimeout;
httpConnectTimeoutMS = connectTimeout;
}
/**
* List all existing indexes
* return an JSON Object in the form:
* { "items": [ {"name": "contacts", "createdAt": "2013-01-18T15:33:13.556Z"},
* {"name": "notes", "createdAt": "2013-01-18T15:33:13.556Z"}]}
*/
public JSONObject listIndexes() throws AlgoliaException {
return getRequest("/1/indexes/", false);
}
/**
* Delete an index
*
* @param indexName the name of index to delete
* return an object containing a "deletedAt" attribute
*/
public JSONObject deleteIndex(String indexName) throws AlgoliaException {
try {
return deleteRequest("/1/indexes/" + URLEncoder.encode(indexName, "UTF-8"), true);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
}
/**
* Move an existing index.
*
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
*/
public JSONObject moveIndex(String srcIndexName, String dstIndexName) throws AlgoliaException {
return operationOnIndex("move", srcIndexName, dstIndexName);
}
/**
* Copy an existing index.
*
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
*/
public JSONObject copyIndex(String srcIndexName, String dstIndexName) throws AlgoliaException {
return operationOnIndex("copy", srcIndexName, dstIndexName);
}
private JSONObject operationOnIndex(String operation, String srcIndexName, String dstIndexName) throws AlgoliaException {
try {
JSONObject content = new JSONObject();
content.put("operation", operation);
content.put("destination", dstIndexName);
return postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString(), true, false);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
} catch (JSONException e) {
throw new AlgoliaException(e.getMessage()); // $COVERAGE-IGNORE$
}
}
public enum LogType {
/// all query logs
LOG_QUERY,
/// all build logs
LOG_BUILD,
/// all error logs
LOG_ERROR,
/// all logs
LOG_ALL
}
/**
* Return 10 last log entries.
*/
public JSONObject getLogs() throws AlgoliaException {
return getRequest("/1/logs", false);
}
/**
* Return last logs entries.
*
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
*/
public JSONObject getLogs(int offset, int length) throws AlgoliaException {
return getLogs(offset, length, LogType.LOG_ALL);
}
/**
* Return last logs entries.
*
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
* @param onlyErrors Retrieve only logs with an httpCode different than 200 and 201
*/
public JSONObject getLogs(int offset, int length, boolean onlyErrors) throws AlgoliaException {
return getLogs(offset, length, onlyErrors ? LogType.LOG_ERROR : LogType.LOG_ALL);
}
/**
* Return last logs entries.
*
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
* @param logType Specify the type of log to retrieve
*/
public JSONObject getLogs(int offset, int length, LogType logType) throws AlgoliaException {
String type = null;
switch (logType) {
case LOG_BUILD:
type = "build";
break;
case LOG_QUERY:
type = "query";
break;
case LOG_ERROR:
type = "error";
break;
case LOG_ALL:
type = "all";
break;
}
return getRequest("/1/logs?offset=" + offset + "&length=" + length + "&type=" + type, false);
}
/**
* Get the index object initialized (no server call needed for initialization)
*
* @param indexName the name of index
*/
public Index initIndex(String indexName) {
return new Index(this, indexName);
}
/**
* List all existing user keys with their associated ACLs
*/
public JSONObject listUserKeys() throws AlgoliaException {
return getRequest("/1/keys", false);
}
/**
* Get ACL of a user key
*/
public JSONObject getUserKeyACL(String key) throws AlgoliaException {
return getRequest("/1/keys/" + key, false);
}
/**
* Delete an existing user key
*/
public JSONObject deleteUserKey(String key) throws AlgoliaException {
return deleteRequest("/1/keys/" + key, true);
}
/**
* Create a new user key
*
* @param params the list of parameters for this key. Defined by a JSONObject that
* can contains the following values:
* - acl: array of string
* - indices: array of string
* - validity: int
* - referers: array of string
* - description: string
* - maxHitsPerQuery: integer
* - queryParameters: string
* - maxQueriesPerIPPerHour: integer
*/
public JSONObject addUserKey(JSONObject params) throws AlgoliaException {
return postRequest("/1/keys", params.toString(), true, false);
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
*/
public JSONObject addUserKey(List<String> acls) throws AlgoliaException {
return addUserKey(acls, 0, 0, 0, null);
}
/**
* Update a user key
*
* @param params the list of parameters for this key. Defined by a JSONObject that
* can contains the following values:
* - acl: array of string
* - indices: array of string
* - validity: int
* - referers: array of string
* - description: string
* - maxHitsPerQuery: integer
* - queryParameters: string
* - maxQueriesPerIPPerHour: integer
*/
public JSONObject updateUserKey(String key, JSONObject params) throws AlgoliaException {
return putRequest("/1/keys/" + key, params.toString(), true);
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
*/
public JSONObject updateUserKey(String key, List<String> acls) throws AlgoliaException {
return updateUserKey(key, acls, 0, 0, 0, null);
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
*/
public JSONObject addUserKey(List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery) throws AlgoliaException {
return addUserKey(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, null);
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
*/
public JSONObject updateUserKey(String key, List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery) throws AlgoliaException {
return updateUserKey(key, acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, null);
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
* @param indexes the list of targeted indexes
*/
public JSONObject addUserKey(List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) throws AlgoliaException {
JSONObject jsonObject = generateUserKeyJson(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, indexes);
return addUserKey(jsonObject);
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
* @param indexes the list of targeted indexes
*/
public JSONObject updateUserKey(String key, List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) throws AlgoliaException {
JSONObject jsonObject = generateUserKeyJson(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, indexes);
return updateUserKey(key, jsonObject);
}
private JSONObject generateUserKeyJson(List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) {
JSONArray array = new JSONArray(acls);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("acl", array);
jsonObject.put("validity", validity);
jsonObject.put("maxQueriesPerIPPerHour", maxQueriesPerIPPerHour);
jsonObject.put("maxHitsPerQuery", maxHitsPerQuery);
if (indexes != null) {
jsonObject.put("indexes", new JSONArray(indexes));
}
} catch (JSONException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
return jsonObject;
}
/**
* Generate a secured and public API Key from a list of tagFilters and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param tagFilters the list of tags applied to the query (used as security)
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @deprecated Use `generateSecuredApiKey(String privateApiKey, Query query)` version
*/
@Deprecated
public String generateSecuredApiKey(String privateApiKey, String tagFilters) throws NoSuchAlgorithmException, InvalidKeyException {
if (!tagFilters.contains("="))
return generateSecuredApiKey(privateApiKey, new Query().setTagFilters(tagFilters), null);
else {
return Base64.encodeBase64String(String.format("%s%s", hmac(privateApiKey, tagFilters), tagFilters).getBytes(Charset.forName("UTF8")));
}
}
/**
* Generate a secured and public API Key from a query and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param query contains the parameter applied to the query (used as security)
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public String generateSecuredApiKey(String privateApiKey, Query query) throws NoSuchAlgorithmException, InvalidKeyException {
return generateSecuredApiKey(privateApiKey, query, null);
}
/**
* Generate a secured and public API Key from a list of tagFilters and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param tagFilters the list of tags applied to the query (used as security)
* @param userToken an optional token identifying the current user
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws AlgoliaException
* @deprecated Use `generateSecuredApiKey(String privateApiKey, Query query, String userToken)` version
*/
@Deprecated
public String generateSecuredApiKey(String privateApiKey, String tagFilters, String userToken) throws NoSuchAlgorithmException, InvalidKeyException, AlgoliaException {
if (!tagFilters.contains("="))
return generateSecuredApiKey(privateApiKey, new Query().setTagFilters(tagFilters), userToken);
else {
if (userToken != null && userToken.length() > 0) {
try {
tagFilters = String.format("%s%s%s", tagFilters, "&userToken=", URLEncoder.encode(userToken, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AlgoliaException(e.getMessage());
}
}
return Base64.encodeBase64String(String.format("%s%s", hmac(privateApiKey, tagFilters), tagFilters).getBytes(Charset.forName("UTF8")));
}
}
/**
* Generate a secured and public API Key from a query and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param query contains the parameter applied to the query (used as security)
* @param userToken an optional token identifying the current user
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public String generateSecuredApiKey(String privateApiKey, Query query, String userToken) throws NoSuchAlgorithmException, InvalidKeyException {
if (userToken != null && userToken.length() > 0) {
query.setUserToken(userToken);
}
String queryStr = query.getQueryString();
String key = hmac(privateApiKey, queryStr);
return Base64.encodeBase64String(String.format("%s%s", key, queryStr).getBytes(Charset.forName("UTF8")));
}
static String hmac(String key, String msg) {
Mac hmac;
try {
hmac = Mac.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException e) {
throw new Error(e);
}
try {
hmac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
} catch (InvalidKeyException e) {
throw new Error(e);
}
byte[] rawHmac = hmac.doFinal(msg.getBytes());
byte[] hexBytes = new Hex().encode(rawHmac);
return new String(hexBytes);
}
private enum Method {
GET, POST, PUT, DELETE
}
protected JSONObject getRequest(String url, boolean search) throws AlgoliaException {
return _request(Method.GET, url, null, false, search);
}
protected JSONObject deleteRequest(String url, boolean build) throws AlgoliaException {
return _request(Method.DELETE, url, null, build, false);
}
protected JSONObject postRequest(String url, String obj, boolean build, boolean search) throws AlgoliaException {
return _request(Method.POST, url, obj, build, search);
}
protected JSONObject putRequest(String url, String obj, boolean build) throws AlgoliaException {
return _request(Method.PUT, url, obj, build, false);
}
private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json, List<AlgoliaInnerException> errors, boolean searchTimeout) throws AlgoliaException {
req.reset();
// set URL
try {
req.setURI(new URI("https://" + host + url));
} catch (URISyntaxException e) {
// never reached
throw new IllegalStateException(e);
}
// set auth headers
req.setHeader("Accept-Encoding", "gzip");
req.setHeader("X-Algolia-Application-Id", this.applicationID);
if (forwardAdminAPIKey == null) {
req.setHeader("X-Algolia-API-Key", this.apiKey);
} else {
req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey);
req.setHeader("X-Forwarded-For", this.forwardEndUserIP);
req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey);
}
for (Entry<String, String> entry : headers.entrySet()) {
req.setHeader(entry.getKey(), entry.getValue());
}
// set user agent
req.setHeader("User-Agent", userAgent);
// set JSON entity
if (json != null) {
if (!(req instanceof HttpEntityEnclosingRequestBase)) {
throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity");
}
req.setHeader("Content-type", "application/json");
try {
StringEntity se = new StringEntity(json, "UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
((HttpEntityEnclosingRequestBase) req).setEntity(se);
} catch (Exception e) {
throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$
}
}
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(searchTimeout ? httpSearchTimeoutMS : httpSocketTimeoutMS)
.setConnectTimeout(httpConnectTimeoutMS)
.setConnectionRequestTimeout(httpConnectTimeoutMS)
.build();
req.setConfig(config);
HttpResponse response;
try {
response = httpClient.execute(req);
} catch (IOException e) {
// on error continue on the next host
if (verbose) {
System.out.println(String.format("%s: %s=%s", host, e.getClass().getName(), e.getMessage()));
}
errors.add(new AlgoliaInnerException(host, e));
return null;
}
try {
int code = response.getStatusLine().getStatusCode();
if (code / 100 == 4) {
String message = "";
try {
message = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (code == 400) {
throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request");
} else if (code == 403) {
throw new AlgoliaException(code, message.length() > 0 ? message : "Invalid Application-ID or API-Key");
} else if (code == 404) {
throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist");
} else {
throw new AlgoliaException(code, message.length() > 0 ? message : "Error");
}
}
if (code / 100 != 2) {
try {
if (verbose) {
System.out.println(String.format("%s: %s", host, EntityUtils.toString(response.getEntity())));
}
errors.add(new AlgoliaInnerException(host, EntityUtils.toString(response.getEntity())));
} catch (IOException e) {
if (verbose) {
System.out.println(String.format("%s: %s", host, String.valueOf(code)));
}
errors.add(new AlgoliaInnerException(host, e));
}
// KO, continue
return null;
}
try {
InputStream istream = response.getEntity().getContent();
String encoding = response.getEntity().getContentEncoding() != null ? response.getEntity().getContentEncoding().getValue() : null;
if (encoding != null && encoding.contains("gzip")) {
istream = new GZIPInputStream(istream);
}
InputStreamReader is = new InputStreamReader(istream, "UTF-8");
StringBuilder jsonRaw = new StringBuilder();
char[] buffer = new char[4096];
int read;
while ((read = is.read(buffer)) > 0) {
jsonRaw.append(buffer, 0, read);
}
is.close();
return new JSONObject(jsonRaw.toString());
} catch (IOException e) {
if (verbose) {
System.out.println(String.format("%s: %s=%s", host, e.getClass().getName(), e.getMessage()));
}
errors.add(new AlgoliaInnerException(host, e));
return null;
} catch (JSONException e) {
throw new AlgoliaException("JSON decode error:" + e.getMessage());
}
} finally {
req.releaseConnection();
}
}
private JSONObject _request(Method m, String url, String json, boolean build, boolean search) throws AlgoliaException {
HttpRequestBase req;
switch (m) {
case DELETE:
req = new HttpDelete();
break;
case GET:
req = new HttpGet();
break;
case POST:
req = new HttpPost();
break;
case PUT:
req = new HttpPut();
break;
default:
throw new IllegalArgumentException("Method " + m + " is not supported");
}
List<AlgoliaInnerException> errors = new ArrayList<AlgoliaInnerException>();
List<String> hosts = build ? this.buildHostsArray : this.queryHostsArray;
// for each host
for (String host : hosts) {
JSONObject res = _requestByHost(req, host, url, json, errors, search);
if (res != null) {
return res;
}
}
throw AlgoliaException.from("Hosts unreachable", errors);
}
public static class IndexQuery {
private String index;
private Query query;
public IndexQuery(String index, Query q) {
this.index = index;
this.query = q;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
/**
* This method allows to query multiple indexes with one API call
*/
public JSONObject multipleQueries(List<IndexQuery> queries) throws AlgoliaException {
return multipleQueries(queries, "none");
}
public JSONObject multipleQueries(List<IndexQuery> queries, String strategy) throws AlgoliaException {
try {
JSONArray requests = new JSONArray();
for (IndexQuery indexQuery : queries) {
String paramsString = indexQuery.getQuery().getQueryString();
requests.put(new JSONObject().put("indexName", indexQuery.getIndex()).put("params", paramsString));
}
JSONObject body = new JSONObject().put("requests", requests);
return postRequest("/1/indexes/*/queries?strategy=" + strategy, body.toString(), false, true);
} catch (JSONException e) {
new AlgoliaException(e);
}
return null;
}
/**
* Custom batch
*
* @param actions the array of actions
* @throws AlgoliaException
*/
public JSONObject batch(JSONArray actions) throws AlgoliaException {
return postBatch(actions);
}
/**
* Custom batch
*
* @param actions the array of actions
* @throws AlgoliaException
*/
public JSONObject batch(List<JSONObject> actions) throws AlgoliaException {
return postBatch(actions);
}
private JSONObject postBatch(Object actions) throws AlgoliaException {
try {
JSONObject content = new JSONObject();
content.put("requests", actions);
return postRequest("/1/indexes/*/batch", content.toString(), true, false);
} catch (JSONException e) {
throw new AlgoliaException(e.getMessage());
}
}
}
| Migrate user agent to new format (#82)
| src/main/java/com/algolia/search/saas/APIClient.java | Migrate user agent to new format (#82) | <ide><path>rc/main/java/com/algolia/search/saas/APIClient.java
<ide> import org.apache.http.client.methods.HttpRequestBase;
<ide> import org.apache.http.entity.StringEntity;
<ide> import org.apache.http.impl.client.HttpClientBuilder;
<add>import org.apache.http.impl.client.SystemDefaultCredentialsProvider;
<ide> import org.apache.http.message.BasicHeader;
<ide> import org.apache.http.protocol.HTTP;
<ide> import org.apache.http.util.EntityUtils;
<ide> * @param queryHostsArray the list of hosts that you have received for the service
<ide> */
<ide> public APIClient(String applicationID, String apiKey, List<String> buildHostsArray, List<String> queryHostsArray) {
<del> userAgent = "Algolia for Java " + version;
<add> userAgent = "Algolia for Java (" + version + "); JVM (" + System.getProperty("java.version") + ")";
<ide> verbose = System.getenv("VERBOSE") != null;
<ide> forwardRateLimitAPIKey = forwardAdminAPIKey = forwardEndUserIP = null;
<ide> if (applicationID == null || applicationID.length() == 0) {
<ide> * Allow to modify the user-agent in order to add the user agent of the integration
<ide> */
<ide> public void setUserAgent(String agent, String agentVersion) {
<del> userAgent = String.format("Algolia for Java %s %s (%s)", version, agent, agentVersion);
<add> userAgent = String.format("Algolia for Java (%s); JVM (%s); %s (%s)", version, System.getProperty("java.version"), agent, agentVersion);
<ide> }
<ide>
<ide> /** |
|
Java | lgpl-2.1 | 0f9ddfbaeb20e0cc8bfa5e6008484d6bcc66ed16 | 0 | CreativeMD/LittleTiles | package com.creativemd.littletiles;
import com.creativemd.creativecore.common.entity.EntitySit;
import com.creativemd.creativecore.common.packet.CreativeCorePacket;
import com.creativemd.creativecore.gui.container.SubContainer;
import com.creativemd.creativecore.gui.container.SubGui;
import com.creativemd.creativecore.gui.opener.CustomGuiHandler;
import com.creativemd.creativecore.gui.opener.GuiHandler;
import com.creativemd.littletiles.common.blocks.BlockLTColored;
import com.creativemd.littletiles.common.blocks.BlockLTParticle;
import com.creativemd.littletiles.common.blocks.BlockLTTransparentColored;
import com.creativemd.littletiles.common.blocks.BlockStorageTile;
import com.creativemd.littletiles.common.blocks.BlockTile;
import com.creativemd.littletiles.common.blocks.ItemBlockColored;
import com.creativemd.littletiles.common.blocks.ItemBlockTransparentColored;
import com.creativemd.littletiles.common.command.ExportCommand;
import com.creativemd.littletiles.common.command.ImportCommand;
import com.creativemd.littletiles.common.entity.EntityAnimation;
import com.creativemd.littletiles.common.entity.EntitySizedTNTPrimed;
import com.creativemd.littletiles.common.events.LittleEvent;
import com.creativemd.littletiles.common.gui.SubContainerExport;
import com.creativemd.littletiles.common.gui.SubContainerImport;
import com.creativemd.littletiles.common.gui.SubContainerStorage;
import com.creativemd.littletiles.common.gui.SubGuiExport;
import com.creativemd.littletiles.common.gui.SubGuiImport;
import com.creativemd.littletiles.common.gui.SubGuiStorage;
import com.creativemd.littletiles.common.gui.handler.LittleGuiHandler;
import com.creativemd.littletiles.common.items.ItemBlockTiles;
import com.creativemd.littletiles.common.items.ItemColorTube;
import com.creativemd.littletiles.common.items.ItemHammer;
import com.creativemd.littletiles.common.items.ItemLittleChisel;
import com.creativemd.littletiles.common.items.ItemLittleSaw;
import com.creativemd.littletiles.common.items.ItemLittleWrench;
import com.creativemd.littletiles.common.items.ItemMultiTiles;
import com.creativemd.littletiles.common.items.ItemRecipe;
import com.creativemd.littletiles.common.items.ItemRubberMallet;
import com.creativemd.littletiles.common.items.ItemTileContainer;
import com.creativemd.littletiles.common.items.ItemUtilityKnife;
import com.creativemd.littletiles.common.packet.LittleBlockPacket;
import com.creativemd.littletiles.common.packet.LittleBlockVanillaPacket;
import com.creativemd.littletiles.common.packet.LittleDoorInteractPacket;
import com.creativemd.littletiles.common.packet.LittleEntityRequestPacket;
import com.creativemd.littletiles.common.packet.LittleFlipPacket;
import com.creativemd.littletiles.common.packet.LittleNeighborUpdatePacket;
import com.creativemd.littletiles.common.packet.LittlePlacePacket;
import com.creativemd.littletiles.common.packet.LittleRotatePacket;
import com.creativemd.littletiles.common.structure.LittleStorage;
import com.creativemd.littletiles.common.structure.LittleStructure;
import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles;
import com.creativemd.littletiles.common.tileentity.TileEntityParticle;
import com.creativemd.littletiles.common.utils.LittleTile;
import com.creativemd.littletiles.common.utils.LittleTileBlock;
import com.creativemd.littletiles.common.utils.LittleTileBlockColored;
import com.creativemd.littletiles.common.utils.LittleTileTileEntity;
import com.creativemd.littletiles.common.utils.sorting.LittleTileSortingList;
import com.creativemd.littletiles.server.LittleTilesServer;
import com.google.common.base.Function;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.ForgeModContainer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.network.internal.FMLMessage.EntitySpawnMessage;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Mod(modid = LittleTiles.modid, version = LittleTiles.version, name = "LittleTiles",acceptedMinecraftVersions="")
public class LittleTiles {
@Instance(LittleTiles.modid)
public static LittleTiles instance = new LittleTiles();
@SidedProxy(clientSide = "com.creativemd.littletiles.client.LittleTilesClient", serverSide = "com.creativemd.littletiles.server.LittleTilesServer")
public static LittleTilesServer proxy;
public static final String modid = "littletiles";
public static final String version = "1.3.0";
public static BlockTile blockTile = (BlockTile) new BlockTile(Material.ROCK).setRegistryName("BlockLittleTiles");
public static Block coloredBlock = new BlockLTColored().setRegistryName("LTColoredBlock").setUnlocalizedName("LTColoredBlock");
public static Block transparentColoredBlock = new BlockLTTransparentColored().setRegistryName("LTTransparentColoredBlock").setUnlocalizedName("LTTransparentColoredBlock");
public static Block storageBlock = new BlockStorageTile().setRegistryName("LTStorageBlockTile").setUnlocalizedName("LTStorageBlockTile");
public static Block particleBlock = new BlockLTParticle().setRegistryName("LTParticleBlock").setUnlocalizedName("LTParticleBlock");
public static Item hammer = new ItemHammer().setUnlocalizedName("LTHammer");
public static Item recipe = new ItemRecipe().setUnlocalizedName("LTRecipe");
public static Item multiTiles = new ItemMultiTiles().setUnlocalizedName("LTMultiTiles");
public static Item saw = new ItemLittleSaw().setUnlocalizedName("LTSaw");
public static Item container = new ItemTileContainer().setUnlocalizedName("LTContainer");
public static Item wrench = new ItemLittleWrench().setUnlocalizedName("LTWrench");
public static Item chisel = new ItemLittleChisel().setUnlocalizedName("LTChisel");
public static Item colorTube = new ItemColorTube().setUnlocalizedName("LTColorTube");
public static Item rubberMallet = new ItemRubberMallet().setUnlocalizedName("LTRubberMallet");
public static Item utilityKnife = new ItemUtilityKnife().setUnlocalizedName("LTUtilityKnife");
@EventHandler
public void PreInit(FMLPreInitializationEvent event)
{
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
LittleTile.setGridSize(config.getInt("gridSize", "Core", 16, 1, Integer.MAX_VALUE, "ATTENTION! This needs be equal for every client. Backup your world. This will make your tiles either shrink down or increase in size!"));
config.save();
proxy.loadSidePre();
}
@EventHandler
public void Init(FMLInitializationEvent event)
{
ForgeModContainer.fullBoundingBoxLadders = true;
GameRegistry.registerItem(hammer, "hammer");
GameRegistry.registerItem(recipe, "recipe");
GameRegistry.registerItem(saw, "saw");
GameRegistry.registerItem(container, "container");
GameRegistry.registerItem(wrench, "wrench");
GameRegistry.registerItem(chisel, "chisel");
GameRegistry.registerItem(colorTube, "colorTube");
GameRegistry.registerItem(rubberMallet, "rubberMallet");
//GameRegistry.registerBlock(coloredBlock, "LTColoredBlock");
GameRegistry.registerBlock(coloredBlock, ItemBlockColored.class);
GameRegistry.registerBlock(transparentColoredBlock, ItemBlockTransparentColored.class);
GameRegistry.registerBlock(blockTile, ItemBlockTiles.class);
GameRegistry.registerBlock(storageBlock);
//GameRegistry.registerBlock(particleBlock);
GameRegistry.registerItem(multiTiles, "multiTiles");
GameRegistry.registerItem(utilityKnife, "utilityKnife");
GameRegistry.registerTileEntity(TileEntityLittleTiles.class, "LittleTilesTileEntity");
GameRegistry.registerTileEntity(TileEntityParticle.class, "LittleTilesParticle");
LittleTile.registerLittleTile(LittleTileBlock.class, "BlockTileBlock");
LittleTile.registerLittleTile(LittleTileTileEntity.class, "BlockTileEntity");
LittleTile.registerLittleTile(LittleTileBlockColored.class, "BlockTileColored");
GuiHandler.registerGuiHandler("littleStorageStructure", new LittleGuiHandler() {
@Override
@SideOnly(Side.CLIENT)
public SubGui getGui(EntityPlayer player, NBTTagCompound nbt, LittleTile tile) {
if(tile.isStructureBlock && tile.structure instanceof LittleStorage)
return new SubGuiStorage((LittleStorage) tile.structure);
return null;
}
@Override
public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt, LittleTile tile) {
if(tile.isStructureBlock && tile.structure instanceof LittleStorage)
return new SubContainerStorage(player, (LittleStorage) tile.structure);
return null;
}
});
GuiHandler.registerGuiHandler("lt-import", new CustomGuiHandler() {
@Override
@SideOnly(Side.CLIENT)
public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
return new SubGuiImport();
}
@Override
public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
return new SubContainerImport(player);
}
});
GuiHandler.registerGuiHandler("lt-export", new CustomGuiHandler() {
@Override
@SideOnly(Side.CLIENT)
public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
return new SubGuiExport();
}
@Override
public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
return new SubContainerExport(player);
}
});
CreativeCorePacket.registerPacket(LittlePlacePacket.class, "LittlePlace");
CreativeCorePacket.registerPacket(LittleBlockPacket.class, "LittleBlock");
CreativeCorePacket.registerPacket(LittleRotatePacket.class, "LittleRotate");
CreativeCorePacket.registerPacket(LittleFlipPacket.class, "LittleFlip");
CreativeCorePacket.registerPacket(LittleNeighborUpdatePacket.class, "LittleNeighbor");
CreativeCorePacket.registerPacket(LittleBlockVanillaPacket.class, "LittleVanillaBlock");
CreativeCorePacket.registerPacket(LittleDoorInteractPacket.class, "LittleDoor");
CreativeCorePacket.registerPacket(LittleEntityRequestPacket.class, "EntityRequest");
//FMLCommonHandler.instance().bus().register(new LittleEvent());
MinecraftForge.EVENT_BUS.register(new LittleEvent());
LittleStructure.initStructures();
//Recipes
GameRegistry.addRecipe(new ItemStack(recipe, 5), new Object[]
{
"XAX", "AXA", "XAX", 'X', Items.PAPER
});
GameRegistry.addRecipe(new ItemStack(hammer), new Object[]
{
"XXX", "ALA", "ALA", 'X', Items.IRON_INGOT, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(container), new Object[]
{
"XXX", "XHX", "XXX", 'X', Items.IRON_INGOT, 'H', hammer
});
GameRegistry.addRecipe(new ItemStack(saw), new Object[]
{
"AXA", "AXA", "ALA", 'X', Items.IRON_INGOT, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(wrench), new Object[]
{
"AXA", "ALA", "ALA", 'X', Items.IRON_INGOT, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(rubberMallet), new Object[]
{
"XXX", "XLX", "ALA", 'X', Blocks.WOOL, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(colorTube), new Object[]
{
"XXX", "XLX", "XXX", 'X', Items.DYE, 'L', Items.IRON_INGOT
});
GameRegistry.addRecipe(new ItemStack(utilityKnife), new Object[]
{
"XAA", "ALA", "AAL", 'X', Items.IRON_INGOT, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 0), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 1), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.SANDSTONE
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 2), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.COBBLESTONE
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 3), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.DIRT
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 4), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.GRAVEL
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 5), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.BRICK_BLOCK
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 6), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.STONE
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 7), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', new ItemStack(Blocks.STONEBRICK, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 8), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', new ItemStack(Blocks.STONEBRICK, 1, 3)
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 9), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', new ItemStack(Blocks.STONEBRICK, 1, 2)
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 10), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.HARDENED_CLAY
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 11), new Object[]
{
"XGX", "GBG", "XGX", 'G', Items.GLOWSTONE_DUST, 'B', new ItemStack(coloredBlock, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 5, 0), new Object[]
{
"SXS", "XGX", "SXS", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0), 'G', Blocks.GLASS
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 5, 1), new Object[]
{
"SXS", "XSX", "SXS", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 3, 2), new Object[]
{
"SSS", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 2, 3), new Object[]
{
"SS", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 1, 4), new Object[]
{
"S", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0)
});
//Water block
GameRegistry.addShapelessRecipe(new ItemStack(transparentColoredBlock, 1, BlockLTTransparentColored.EnumType.water.ordinal()), Items.WATER_BUCKET);
GameRegistry.addShapelessRecipe(new ItemStack(transparentColoredBlock, 1, BlockLTColored.EnumType.lava.ordinal()), Items.LAVA_BUCKET);
GameRegistry.addRecipe(new ItemStack(storageBlock, 1), new Object[]
{
"C", 'C', Blocks.CHEST
});
//Entity
EntityRegistry.registerModEntity(EntitySizedTNTPrimed.class, "sizedTNT", 0, this, 250, 250, true);
EntityRegistry.registerModEntity(EntityAnimation.class, "animation", 1, this, 2000, 250, true);
proxy.loadSide();
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event)
{
event.registerServerCommand(new ExportCommand());
event.registerServerCommand(new ImportCommand());
}
@EventHandler
public void LoadComplete(FMLLoadCompleteEvent event)
{
LittleTileSortingList.initVanillaBlocks();
}
}
| src/main/java/com/creativemd/littletiles/LittleTiles.java | package com.creativemd.littletiles;
import com.creativemd.creativecore.common.entity.EntitySit;
import com.creativemd.creativecore.common.packet.CreativeCorePacket;
import com.creativemd.creativecore.gui.container.SubContainer;
import com.creativemd.creativecore.gui.container.SubGui;
import com.creativemd.creativecore.gui.opener.CustomGuiHandler;
import com.creativemd.creativecore.gui.opener.GuiHandler;
import com.creativemd.littletiles.common.blocks.BlockLTColored;
import com.creativemd.littletiles.common.blocks.BlockLTParticle;
import com.creativemd.littletiles.common.blocks.BlockLTTransparentColored;
import com.creativemd.littletiles.common.blocks.BlockStorageTile;
import com.creativemd.littletiles.common.blocks.BlockTile;
import com.creativemd.littletiles.common.blocks.ItemBlockColored;
import com.creativemd.littletiles.common.blocks.ItemBlockTransparentColored;
import com.creativemd.littletiles.common.command.ExportCommand;
import com.creativemd.littletiles.common.command.ImportCommand;
import com.creativemd.littletiles.common.entity.EntityAnimation;
import com.creativemd.littletiles.common.entity.EntitySizedTNTPrimed;
import com.creativemd.littletiles.common.events.LittleEvent;
import com.creativemd.littletiles.common.gui.SubContainerExport;
import com.creativemd.littletiles.common.gui.SubContainerImport;
import com.creativemd.littletiles.common.gui.SubContainerStorage;
import com.creativemd.littletiles.common.gui.SubGuiExport;
import com.creativemd.littletiles.common.gui.SubGuiImport;
import com.creativemd.littletiles.common.gui.SubGuiStorage;
import com.creativemd.littletiles.common.gui.handler.LittleGuiHandler;
import com.creativemd.littletiles.common.items.ItemBlockTiles;
import com.creativemd.littletiles.common.items.ItemColorTube;
import com.creativemd.littletiles.common.items.ItemHammer;
import com.creativemd.littletiles.common.items.ItemLittleChisel;
import com.creativemd.littletiles.common.items.ItemLittleSaw;
import com.creativemd.littletiles.common.items.ItemLittleWrench;
import com.creativemd.littletiles.common.items.ItemMultiTiles;
import com.creativemd.littletiles.common.items.ItemRecipe;
import com.creativemd.littletiles.common.items.ItemRubberMallet;
import com.creativemd.littletiles.common.items.ItemTileContainer;
import com.creativemd.littletiles.common.items.ItemUtilityKnife;
import com.creativemd.littletiles.common.packet.LittleBlockPacket;
import com.creativemd.littletiles.common.packet.LittleBlockVanillaPacket;
import com.creativemd.littletiles.common.packet.LittleDoorInteractPacket;
import com.creativemd.littletiles.common.packet.LittleEntityRequestPacket;
import com.creativemd.littletiles.common.packet.LittleFlipPacket;
import com.creativemd.littletiles.common.packet.LittleNeighborUpdatePacket;
import com.creativemd.littletiles.common.packet.LittlePlacePacket;
import com.creativemd.littletiles.common.packet.LittleRotatePacket;
import com.creativemd.littletiles.common.structure.LittleStorage;
import com.creativemd.littletiles.common.structure.LittleStructure;
import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles;
import com.creativemd.littletiles.common.tileentity.TileEntityParticle;
import com.creativemd.littletiles.common.utils.LittleTile;
import com.creativemd.littletiles.common.utils.LittleTileBlock;
import com.creativemd.littletiles.common.utils.LittleTileBlockColored;
import com.creativemd.littletiles.common.utils.LittleTileTileEntity;
import com.creativemd.littletiles.common.utils.sorting.LittleTileSortingList;
import com.creativemd.littletiles.server.LittleTilesServer;
import com.google.common.base.Function;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.ForgeModContainer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.network.internal.FMLMessage.EntitySpawnMessage;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Mod(modid = LittleTiles.modid, version = LittleTiles.version, name = "LittleTiles",acceptedMinecraftVersions="")
public class LittleTiles {
@Instance(LittleTiles.modid)
public static LittleTiles instance = new LittleTiles();
@SidedProxy(clientSide = "com.creativemd.littletiles.client.LittleTilesClient", serverSide = "com.creativemd.littletiles.server.LittleTilesServer")
public static LittleTilesServer proxy;
public static final String modid = "littletiles";
public static final String version = "1.3.0";
public static BlockTile blockTile = (BlockTile) new BlockTile(Material.ROCK).setRegistryName("BlockLittleTiles");
public static Block coloredBlock = new BlockLTColored().setRegistryName("LTColoredBlock").setUnlocalizedName("LTColoredBlock");
public static Block transparentColoredBlock = new BlockLTTransparentColored().setRegistryName("LTTransparentColoredBlock").setUnlocalizedName("LTTransparentColoredBlock");
public static Block storageBlock = new BlockStorageTile().setRegistryName("LTStorageBlockTile").setUnlocalizedName("LTStorageBlockTile");
public static Block particleBlock = new BlockLTParticle().setRegistryName("LTParticleBlock").setUnlocalizedName("LTParticleBlock");
public static Item hammer = new ItemHammer().setUnlocalizedName("LTHammer").setRegistryName("hammer");
public static Item recipe = new ItemRecipe().setUnlocalizedName("LTRecipe").setRegistryName("recipe");
public static Item multiTiles = new ItemMultiTiles().setUnlocalizedName("LTMultiTiles").setRegistryName("multiTiles");
public static Item saw = new ItemLittleSaw().setUnlocalizedName("LTSaw").setRegistryName("saw");
public static Item container = new ItemTileContainer().setUnlocalizedName("LTContainer").setRegistryName("container");
public static Item wrench = new ItemLittleWrench().setUnlocalizedName("LTWrench").setRegistryName("wrench");
public static Item chisel = new ItemLittleChisel().setUnlocalizedName("LTChisel").setRegistryName("chisel");
public static Item colorTube = new ItemColorTube().setUnlocalizedName("LTColorTube").setRegistryName("colorTube");
public static Item rubberMallet = new ItemRubberMallet().setUnlocalizedName("LTRubberMallet").setRegistryName("rubberMallet");
public static Item utilityKnife = new ItemUtilityKnife().setUnlocalizedName("LTUtilityKnife").setRegistryName("utilityKnife");
@EventHandler
public void PreInit(FMLPreInitializationEvent event)
{
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
LittleTile.setGridSize(config.getInt("gridSize", "Core", 16, 1, Integer.MAX_VALUE, "ATTENTION! This needs be equal for every client. Backup your world. This will make your tiles either shrink down or increase in size!"));
config.save();
proxy.loadSidePre();
}
@EventHandler
public void Init(FMLInitializationEvent event)
{
ForgeModContainer.fullBoundingBoxLadders = true;
GameRegistry.registerItem(hammer, "hammer");
GameRegistry.registerItem(recipe, "recipe");
GameRegistry.registerItem(saw, "saw");
GameRegistry.registerItem(container, "container");
GameRegistry.registerItem(wrench, "wrench");
GameRegistry.registerItem(chisel, "chisel");
GameRegistry.registerItem(colorTube, "colorTube");
GameRegistry.registerItem(rubberMallet, "rubberMallet");
//GameRegistry.registerBlock(coloredBlock, "LTColoredBlock");
GameRegistry.registerBlock(coloredBlock, ItemBlockColored.class);
GameRegistry.registerBlock(transparentColoredBlock, ItemBlockTransparentColored.class);
GameRegistry.registerBlock(blockTile, ItemBlockTiles.class);
GameRegistry.registerBlock(storageBlock);
//GameRegistry.registerBlock(particleBlock);
GameRegistry.registerItem(multiTiles, "multiTiles");
GameRegistry.registerItem(utilityKnife, "utilityKnife");
GameRegistry.registerTileEntity(TileEntityLittleTiles.class, "LittleTilesTileEntity");
GameRegistry.registerTileEntity(TileEntityParticle.class, "LittleTilesParticle");
LittleTile.registerLittleTile(LittleTileBlock.class, "BlockTileBlock");
LittleTile.registerLittleTile(LittleTileTileEntity.class, "BlockTileEntity");
LittleTile.registerLittleTile(LittleTileBlockColored.class, "BlockTileColored");
GuiHandler.registerGuiHandler("littleStorageStructure", new LittleGuiHandler() {
@Override
@SideOnly(Side.CLIENT)
public SubGui getGui(EntityPlayer player, NBTTagCompound nbt, LittleTile tile) {
if(tile.isStructureBlock && tile.structure instanceof LittleStorage)
return new SubGuiStorage((LittleStorage) tile.structure);
return null;
}
@Override
public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt, LittleTile tile) {
if(tile.isStructureBlock && tile.structure instanceof LittleStorage)
return new SubContainerStorage(player, (LittleStorage) tile.structure);
return null;
}
});
GuiHandler.registerGuiHandler("lt-import", new CustomGuiHandler() {
@Override
@SideOnly(Side.CLIENT)
public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
return new SubGuiImport();
}
@Override
public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
return new SubContainerImport(player);
}
});
GuiHandler.registerGuiHandler("lt-export", new CustomGuiHandler() {
@Override
@SideOnly(Side.CLIENT)
public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
return new SubGuiExport();
}
@Override
public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
return new SubContainerExport(player);
}
});
CreativeCorePacket.registerPacket(LittlePlacePacket.class, "LittlePlace");
CreativeCorePacket.registerPacket(LittleBlockPacket.class, "LittleBlock");
CreativeCorePacket.registerPacket(LittleRotatePacket.class, "LittleRotate");
CreativeCorePacket.registerPacket(LittleFlipPacket.class, "LittleFlip");
CreativeCorePacket.registerPacket(LittleNeighborUpdatePacket.class, "LittleNeighbor");
CreativeCorePacket.registerPacket(LittleBlockVanillaPacket.class, "LittleVanillaBlock");
CreativeCorePacket.registerPacket(LittleDoorInteractPacket.class, "LittleDoor");
CreativeCorePacket.registerPacket(LittleEntityRequestPacket.class, "EntityRequest");
//FMLCommonHandler.instance().bus().register(new LittleEvent());
MinecraftForge.EVENT_BUS.register(new LittleEvent());
LittleStructure.initStructures();
//Recipes
GameRegistry.addRecipe(new ItemStack(recipe, 5), new Object[]
{
"XAX", "AXA", "XAX", 'X', Items.PAPER
});
GameRegistry.addRecipe(new ItemStack(hammer), new Object[]
{
"XXX", "ALA", "ALA", 'X', Items.IRON_INGOT, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(container), new Object[]
{
"XXX", "XHX", "XXX", 'X', Items.IRON_INGOT, 'H', hammer
});
GameRegistry.addRecipe(new ItemStack(saw), new Object[]
{
"AXA", "AXA", "ALA", 'X', Items.IRON_INGOT, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(wrench), new Object[]
{
"AXA", "ALA", "ALA", 'X', Items.IRON_INGOT, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(rubberMallet), new Object[]
{
"XXX", "XLX", "ALA", 'X', Blocks.WOOL, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(colorTube), new Object[]
{
"XXX", "XLX", "XXX", 'X', Items.DYE, 'L', Items.IRON_INGOT
});
GameRegistry.addRecipe(new ItemStack(utilityKnife), new Object[]
{
"XAA", "ALA", "AAL", 'X', Items.IRON_INGOT, 'L', new ItemStack(Items.DYE, 1, 4)
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 0), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 1), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.SANDSTONE
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 2), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.COBBLESTONE
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 3), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.DIRT
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 4), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.GRAVEL
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 5), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.BRICK_BLOCK
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 6), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.STONE
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 7), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', new ItemStack(Blocks.STONEBRICK, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 8), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', new ItemStack(Blocks.STONEBRICK, 1, 3)
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 9), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', new ItemStack(Blocks.STONEBRICK, 1, 2)
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 10), new Object[]
{
"XXX", "XAX", "XXX", 'X', Blocks.QUARTZ_BLOCK, 'A', Blocks.HARDENED_CLAY
});
GameRegistry.addRecipe(new ItemStack(coloredBlock, 9, 11), new Object[]
{
"XGX", "GBG", "XGX", 'G', Items.GLOWSTONE_DUST, 'B', new ItemStack(coloredBlock, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 5, 0), new Object[]
{
"SXS", "XGX", "SXS", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0), 'G', Blocks.GLASS
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 5, 1), new Object[]
{
"SXS", "XSX", "SXS", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 3, 2), new Object[]
{
"SSS", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 2, 3), new Object[]
{
"SS", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0)
});
GameRegistry.addRecipe(new ItemStack(transparentColoredBlock, 1, 4), new Object[]
{
"S", 'S', new ItemStack(Blocks.STAINED_GLASS, 1, 0)
});
//Water block
GameRegistry.addShapelessRecipe(new ItemStack(transparentColoredBlock, 1, BlockLTTransparentColored.EnumType.water.ordinal()), Items.WATER_BUCKET);
GameRegistry.addShapelessRecipe(new ItemStack(transparentColoredBlock, 1, BlockLTColored.EnumType.lava.ordinal()), Items.LAVA_BUCKET);
GameRegistry.addRecipe(new ItemStack(storageBlock, 1), new Object[]
{
"C", 'C', Blocks.CHEST
});
//Entity
EntityRegistry.registerModEntity(EntitySizedTNTPrimed.class, "sizedTNT", 0, this, 250, 250, true);
EntityRegistry.registerModEntity(EntityAnimation.class, "animation", 1, this, 2000, 250, true);
proxy.loadSide();
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event)
{
event.registerServerCommand(new ExportCommand());
event.registerServerCommand(new ImportCommand());
}
@EventHandler
public void LoadComplete(FMLLoadCompleteEvent event)
{
LittleTileSortingList.initVanillaBlocks();
}
}
| Fixed startup crash caused by setting registry names for item
| src/main/java/com/creativemd/littletiles/LittleTiles.java | Fixed startup crash caused by setting registry names for item | <ide><path>rc/main/java/com/creativemd/littletiles/LittleTiles.java
<ide> public static Block storageBlock = new BlockStorageTile().setRegistryName("LTStorageBlockTile").setUnlocalizedName("LTStorageBlockTile");
<ide> public static Block particleBlock = new BlockLTParticle().setRegistryName("LTParticleBlock").setUnlocalizedName("LTParticleBlock");
<ide>
<del> public static Item hammer = new ItemHammer().setUnlocalizedName("LTHammer").setRegistryName("hammer");
<del> public static Item recipe = new ItemRecipe().setUnlocalizedName("LTRecipe").setRegistryName("recipe");
<del> public static Item multiTiles = new ItemMultiTiles().setUnlocalizedName("LTMultiTiles").setRegistryName("multiTiles");
<del> public static Item saw = new ItemLittleSaw().setUnlocalizedName("LTSaw").setRegistryName("saw");
<del> public static Item container = new ItemTileContainer().setUnlocalizedName("LTContainer").setRegistryName("container");
<del> public static Item wrench = new ItemLittleWrench().setUnlocalizedName("LTWrench").setRegistryName("wrench");
<del> public static Item chisel = new ItemLittleChisel().setUnlocalizedName("LTChisel").setRegistryName("chisel");
<del> public static Item colorTube = new ItemColorTube().setUnlocalizedName("LTColorTube").setRegistryName("colorTube");
<del> public static Item rubberMallet = new ItemRubberMallet().setUnlocalizedName("LTRubberMallet").setRegistryName("rubberMallet");
<del> public static Item utilityKnife = new ItemUtilityKnife().setUnlocalizedName("LTUtilityKnife").setRegistryName("utilityKnife");
<add> public static Item hammer = new ItemHammer().setUnlocalizedName("LTHammer");
<add> public static Item recipe = new ItemRecipe().setUnlocalizedName("LTRecipe");
<add> public static Item multiTiles = new ItemMultiTiles().setUnlocalizedName("LTMultiTiles");
<add> public static Item saw = new ItemLittleSaw().setUnlocalizedName("LTSaw");
<add> public static Item container = new ItemTileContainer().setUnlocalizedName("LTContainer");
<add> public static Item wrench = new ItemLittleWrench().setUnlocalizedName("LTWrench");
<add> public static Item chisel = new ItemLittleChisel().setUnlocalizedName("LTChisel");
<add> public static Item colorTube = new ItemColorTube().setUnlocalizedName("LTColorTube");
<add> public static Item rubberMallet = new ItemRubberMallet().setUnlocalizedName("LTRubberMallet");
<add> public static Item utilityKnife = new ItemUtilityKnife().setUnlocalizedName("LTUtilityKnife");
<ide>
<ide> @EventHandler
<ide> public void PreInit(FMLPreInitializationEvent event) |
|
JavaScript | mit | ea2682f69a65e22d3ca0fa644664ffd9e58d9a45 | 0 | arenoir/data,rtablada/data,davidpett/data,arenoir/data,HeroicEric/data,davidpett/data,davidpett/data,swarmbox/data,swarmbox/data,HeroicEric/data,rtablada/data,swarmbox/data,davidpett/data,HeroicEric/data,workmanw/data,rtablada/data,HeroicEric/data,workmanw/data,workmanw/data,arenoir/data,workmanw/data,arenoir/data,rtablada/data,swarmbox/data | import Ember from 'ember';
import { assert, deprecate, warn, runInDebug } from 'ember-data/-debug';
import { PromiseObject } from "../promise-proxies";
import Errors from "../model/errors";
import isEnabled from '../../features';
import RootState from '../model/states';
import {
relationshipsByNameDescriptor,
relatedTypesDescriptor,
relationshipsDescriptor
} from '../relationships/ext';
const {
get,
computed,
Map
} = Ember;
/**
@module ember-data
*/
function findPossibleInverses(type, inverseType, name, relationshipsSoFar) {
let possibleRelationships = relationshipsSoFar || [];
let relationshipMap = get(inverseType, 'relationships');
if (!relationshipMap) { return possibleRelationships; }
let relationships = relationshipMap.get(type.modelName).filter(relationship => {
let optionsForRelationship = inverseType.metaForProperty(relationship.name).options;
if (!optionsForRelationship.inverse) {
return true;
}
return name === optionsForRelationship.inverse;
});
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationships);
}
//Recurse to support polymorphism
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, name, possibleRelationships);
}
return possibleRelationships;
}
function intersection (array1, array2) {
let result = [];
array1.forEach((element) => {
if (array2.indexOf(element) >= 0) {
result.push(element);
}
});
return result;
}
const RESERVED_MODEL_PROPS = [
'currentState', 'data', 'store'
];
const retrieveFromCurrentState = computed('currentState', function(key) {
return get(this._internalModel.currentState, key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
This is the public API of Ember Data models. If you are using Ember Data
in your application, this is the class you should use.
If you are working on Ember Data internals, you most likely want to be dealing
with `InternalModel`
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
const Model = Ember.Object.extend(Ember.Evented, {
_internalModel: null,
store: null,
__defineNonEnumerable(property) {
this[property.name] = property.descriptor.value;
},
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
let record = store.createRecord('model');
record.get('isLoaded'); // true
store.findRecord('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
let record = store.createRecord('model');
record.get('hasDirtyAttributes'); // true
store.findRecord('model', 1).then(function(model) {
model.get('hasDirtyAttributes'); // false
model.set('foo', 'some value');
model.get('hasDirtyAttributes'); // true
});
```
@since 1.13.0
@property hasDirtyAttributes
@type {Boolean}
@readOnly
*/
hasDirtyAttributes: computed('currentState.isDirty', function() {
return this.get('currentState.isDirty');
}),
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
let record = store.createRecord('model');
record.get('isSaving'); // false
let promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`hasDirtyAttributes` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the
change has persisted.
Example
```javascript
let record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('hasDirtyAttributes'); // true
record.get('isSaving'); // false
// Persisting the deletion
let promise = record.save();
record.get('isDeleted'); // true
record.get('isSaving'); // true
// Deletion Persisted
promise.then(function() {
record.get('isDeleted'); // true
record.get('isSaving'); // false
record.get('hasDirtyAttributes'); // false
});
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
let record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state.
A record will be in the `valid` state when the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
let record = store.createRecord('model');
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend for any reason other than a server-side
validation error.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record from the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
let record = store.createRecord('model');
record.get('id'); // null
store.findRecord('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
currentState: RootState.empty,
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
contains keys corresponding to the invalid property names
and values which are arrays of Javascript objects with two keys:
- `message` A string containing the error message from the backend
- `attribute` The name of the property associated with this error message
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
record.get('errors').get('foo');
// [{message: 'foo should be a number.', attribute: 'foo'}]
});
```
The `errors` property us useful for displaying error messages to
the user.
```handlebars
<label>Username: {{input value=username}} </label>
{{#each model.errors.username as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each model.errors.email as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
```
You can also access the special `messages` property on the error
object to get an array of all the error strings.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property errors
@type {DS.Errors}
*/
errors: computed(function() {
let errors = Errors.create();
errors._registerHandlers(this._internalModel,
function() {
this.send('becameInvalid');
},
function() {
this.send('becameValid');
});
return errors;
}).readOnly(),
/**
This property holds the `DS.AdapterError` object with which
last adapter operation was rejected.
@property adapterError
@type {DS.AdapterError}
*/
adapterError: null,
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize(options) {
return this._internalModel.createSnapshot().serialize(options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@return {Object} A JSON representation of the object.
*/
toJSON(options) {
// container is for lazy transform lookups
let serializer = this.store.serializerFor('-default');
let snapshot = this._internalModel.createSnapshot();
return serializer.serialize(snapshot, options);
},
/**
Fired when the record is ready to be interacted with,
that is either loaded from the server or created locally.
@event ready
*/
ready: null,
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: null,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: null,
/**
Fired when a new record is commited to the server.
@event didCreate
*/
didCreate: null,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: null,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: null,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: null,
/**
Fired when the record is rolled back.
@event rolledBack
*/
rolledBack: null,
//TODO Do we want to deprecate these?
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send(name, context) {
return this._internalModel.send(name, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo(name) {
return this._internalModel.transitionTo(name);
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollbackAttributes()`
after a delete was made.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
softDelete: function() {
this.controller.get('model').deleteRecord();
},
confirm: function() {
this.controller.get('model').save();
},
undo: function() {
this.controller.get('model').rollbackAttributes();
}
}
});
```
@method deleteRecord
*/
deleteRecord() {
this._internalModel.deleteRecord();
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
delete: function() {
let controller = this.controller;
controller.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
If you pass an object on the `adapterOptions` property of the options
argument it will be passed to your adapter via the snapshot
```js
record.destroyRecord({ adapterOptions: { subscribe: false } });
```
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default MyCustomAdapter.extend({
deleteRecord: function(store, type, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
});
```
@method destroyRecord
@param {Object} options
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord(options) {
this.deleteRecord();
return this.save(options);
},
/**
Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection.
@method unloadRecord
*/
unloadRecord() {
if (this.isDestroyed) { return; }
this._internalModel.unloadRecord();
},
/**
@method _notifyProperties
@private
*/
_notifyProperties(keys) {
Ember.beginPropertyChanges();
let key;
for (let i = 0, length = keys.length; i < length; i++) {
key = keys[i];
this.notifyPropertyChange(key);
}
Ember.endPropertyChanges();
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
The array represents the diff of the canonical state with the local state
of the model. Note: if the model is created locally, the canonical state is
empty since the adapter hasn't acknowledged the attributes yet:
Example
```app/models/mascot.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
isAdmin: DS.attr('boolean', {
defaultValue: false
})
});
```
```javascript
let mascot = store.createRecord('mascot');
mascot.changedAttributes(); // {}
mascot.set('name', 'Tomster');
mascot.changedAttributes(); // { name: [undefined, 'Tomster'] }
mascot.set('isAdmin', true);
mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] }
mascot.save().then(function() {
mascot.changedAttributes(); // {}
mascot.set('isAdmin', false);
mascot.changedAttributes(); // { isAdmin: [true, false] }
});
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes() {
return this._internalModel.changedAttributes();
},
//TODO discuss with tomhuda about events/hooks
//Bring back as hooks?
/**
@method adapterWillCommit
@private
adapterWillCommit: function() {
this.send('willCommit');
},
/**
@method adapterDidDirty
@private
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
*/
/**
If the model `hasDirtyAttributes` this function will discard any unsaved
changes. If the model `isNew` it will be removed from the store.
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollbackAttributes();
record.get('name'); // 'Untitled Document'
```
@since 1.13.0
@method rollbackAttributes
*/
rollbackAttributes() {
this._internalModel.rollbackAttributes();
},
/*
@method _createSnapshot
@private
*/
_createSnapshot() {
return this._internalModel.createSnapshot();
},
toStringExtension() {
return get(this, 'id');
},
/**
Save the record and persist any changes to the record to an
external source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function() {
// Success callback
}, function() {
// Error callback
});
```
If you pass an object on the `adapterOptions` property of the options
argument it will be passed to you adapter via the snapshot
```js
record.save({ adapterOptions: { subscribe: false } });
```
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default MyCustomAdapter.extend({
updateRecord: function(store, type, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
});
```
@method save
@param {Object} options
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save(options) {
return PromiseObject.create({
promise: this._internalModel.save(options).then(() => this)
});
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading.
Example
```app/routes/model/view.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
reload: function() {
this.controller.get('model').reload().then(function(model) {
// do something with the reloaded model
});
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload() {
return PromiseObject.create({
promise: this._internalModel.reload().then(() => this)
});
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param {String} name
*/
trigger(name) {
let fn = this[name];
if (typeof fn === 'function') {
let length = arguments.length;
let args = new Array(length - 1);
for (let i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
fn.apply(this, args)
}
this._super(...arguments);
},
attr() {
assert("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false);
},
/**
Get the reference for the specified belongsTo relationship.
Example
```app/models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
```
```javascript
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
// check if the user relationship is loaded
let isLoaded = userRef.value() !== null;
// get the record of the reference (null if not yet available)
let user = userRef.value();
// get the identifier of the reference
if (userRef.remoteType() === "id") {
let id = userRef.id();
} else if (userRef.remoteType() === "link") {
let link = userRef.link();
}
// load user (via store.findRecord or store.findBelongsTo)
userRef.load().then(...)
// or trigger a reload
userRef.reload().then(...)
// provide data for reference
userRef.push({
type: 'user',
id: 1,
attributes: {
username: "@user"
}
}).then(function(user) {
userRef.value() === user;
});
```
@method belongsTo
@param {String} name of the relationship
@since 2.5.0
@return {BelongsToReference} reference for this relationship
*/
belongsTo(name) {
return this._internalModel.referenceFor('belongsTo', name);
},
/**
Get the reference for the specified hasMany relationship.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
comments: {
data: [
{ type: 'comment', id: 1 },
{ type: 'comment', id: 2 }
]
}
}
}
});
let commentsRef = blog.hasMany('comments');
// check if the comments are loaded already
let isLoaded = commentsRef.value() !== null;
// get the records of the reference (null if not yet available)
let comments = commentsRef.value();
// get the identifier of the reference
if (commentsRef.remoteType() === "ids") {
let ids = commentsRef.ids();
} else if (commentsRef.remoteType() === "link") {
let link = commentsRef.link();
}
// load comments (via store.findMany or store.findHasMany)
commentsRef.load().then(...)
// or trigger a reload
commentsRef.reload().then(...)
// provide data for reference
commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) {
commentsRef.value() === comments;
});
```
@method hasMany
@param {String} name of the relationship
@since 2.5.0
@return {HasManyReference} reference for this relationship
*/
hasMany(name) {
return this._internalModel.referenceFor('hasMany', name);
},
setId: Ember.observer('id', function () {
this._internalModel.setId(this.get('id'));
}),
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo() {
let attributes = ['id'];
let relationships = { };
let expensiveProperties = [];
this.eachAttribute((name, meta) => attributes.push(name));
let groups = [
{
name: 'Attributes',
properties: attributes,
expand: true
}
];
this.eachRelationship((name, relationship) => {
let properties = relationships[relationship.kind];
if (properties === undefined) {
properties = relationships[relationship.kind] = [];
groups.push({
name: relationship.name,
properties,
expand: true
});
}
properties.push(name);
expensiveProperties.push(name);
});
groups.push({
name: 'Flags',
properties: ['isLoaded', 'hasDirtyAttributes', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
});
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
},
notifyBelongsToChanged(key) {
this.notifyPropertyChange(key);
},
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, descriptor);
```
- `name` the name of the current property in the iteration
- `descriptor` the meta object that describes this relationship
The relationship descriptor argument is an object with the following properties.
- **key** <span class="type">String</span> the name of this relationship on the Model
- **kind** <span class="type">String</span> "hasMany" or "belongsTo"
- **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
- **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship
- **type** <span class="type">String</span> the type name of the related Model
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(record, options) {
let json = {};
record.eachRelationship(function(name, descriptor) {
if (descriptor.kind === 'hasMany') {
let serializedHasManyName = name.toUpperCase() + '_IDS';
json[serializedHasManyName] = record.get(name).mapBy('id');
}
});
return json;
}
});
```
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship(callback, binding) {
this.constructor.eachRelationship(callback, binding);
},
relationshipFor(name) {
return get(this.constructor, 'relationshipsByName').get(name);
},
inverseFor(key) {
return this.constructor.inverseFor(key, this.store);
},
notifyHasManyAdded(key) {
//We need to notifyPropertyChange in the adding case because we need to make sure
//we fetch the newly added record in case it is unloaded
//TODO(Igor): Consider whether we could do this only if the record state is unloaded
//Goes away once hasMany is double promisified
this.notifyPropertyChange(key);
},
eachAttribute(callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
/**
@property data
@private
@type {Object}
*/
Object.defineProperty(Model.prototype, 'data', {
get() {
return this._internalModel._data;
}
});
runInDebug(function() {
Model.reopen({
init() {
this._super(...arguments);
if (!this._internalModel) {
throw new Ember.Error('You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.');
}
}
});
});
Model.reopenClass({
isModel: true,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
/**
Represents the model's class name as a string. This can be used to look up the model's class name through
`DS.Store`'s modelFor method.
`modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string.
For example:
```javascript
store.modelFor('post').modelName; // 'post'
store.modelFor('blog-post').modelName; // 'blog-post'
```
The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
keys to underscore (instead of dasherized), you might use the following code:
```javascript
export default const PostSerializer = DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.underscore(modelName);
}
});
```
@property modelName
@type String
@readonly
@static
*/
modelName: null,
/*
These class methods below provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `store.modelFor('post').typeForRelationship('comments', store)` will return `Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@param {store} store an instance of DS.Store
@return {DS.Model} the type of the relationship, or undefined
*/
typeForRelationship(name, store) {
let relationship = get(this, 'relationshipsByName').get(name);
return relationship && store.modelFor(relationship.type);
},
inverseMap: Ember.computed(function() {
return Object.create(null);
}),
/**
Find the relationship which is the inverse of the one asked for.
For example, if you define models like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('message')
});
```
```app/models/message.js
import DS from 'ember-data';
export default DS.Model.extend({
owner: DS.belongsTo('post')
});
```
``` js
store.modelFor('post').inverseFor('comments', store) // { type: App.Message, name: 'owner', kind: 'belongsTo' }
store.modelFor('message').inverseFor('owner', store) // { type: App.Post, name: 'comments', kind: 'hasMany' }
```
@method inverseFor
@static
@param {String} name the name of the relationship
@param {DS.Store} store
@return {Object} the inverse relationship, or null
*/
inverseFor(name, store) {
let inverseMap = get(this, 'inverseMap');
if (inverseMap[name] !== undefined) {
return inverseMap[name];
} else {
let relationship = get(this, 'relationshipsByName').get(name);
if (!relationship) {
inverseMap[name] = null;
return null;
}
let options = relationship.options;
if (options && options.inverse === null) {
// populate the cache with a miss entry so we can skip getting and going
// through `relationshipsByName`
inverseMap[name] = null;
return null;
}
return inverseMap[name] = this._findInverseFor(name, store);
}
},
//Calculate the inverse, ignoring the cache
_findInverseFor(name, store) {
let inverseType = this.typeForRelationship(name, store);
if (!inverseType) {
return null;
}
let propertyMeta = this.metaForProperty(name);
//If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })`
let options = propertyMeta.options;
if (options.inverse === null) { return null; }
let inverseName, inverseKind, inverse;
//If inverse is specified manually, return the inverse
if (options.inverse) {
inverseName = options.inverse;
inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName);
assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.modelName +
"' model. This is most likely due to a missing attribute on your model definition.", !Ember.isNone(inverse));
inverseKind = inverse.kind;
} else {
//No inverse was specified manually, we need to use a heuristic to guess one
if (propertyMeta.parentType && propertyMeta.type === propertyMeta.parentType.modelName) {
warn(`Detected a reflexive relationship by the name of '${name}' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.`, false, {
id: 'ds.model.reflexive-relationship-without-inverse'
});
}
let possibleRelationships = findPossibleInverses(this, inverseType, name);
if (possibleRelationships.length === 0) { return null; }
let filteredRelationships = possibleRelationships.filter((possibleRelationship) => {
let optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options;
return name === optionsForRelationship.inverse;
});
assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " +
inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
filteredRelationships.length < 2);
if (filteredRelationships.length === 1 ) {
possibleRelationships = filteredRelationships;
}
assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " +
this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
possibleRelationships.length === 1);
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
import User from 'app/models/user';
import Post from 'app/models/post';
let relationships = Ember.get(Blog, 'relationships');
relationships.get(User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: relationshipsDescriptor,
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relationshipNames = Ember.get(Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function() {
let names = {
hasMany: [],
belongsTo: []
};
this.eachComputedProperty((name, meta) => {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relatedTypes = Ember.get(Blog, 'relatedTypes');
//=> [ User, Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: relatedTypesDescriptor,
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relationshipsByName = Ember.get(Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: relationshipsByNameDescriptor,
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
```
```js
import Ember from 'ember';
import Blog from 'app/models/blog';
let fields = Ember.get(Blog, 'fields');
fields.forEach(function(kind, field) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function() {
let map = Map.create();
this.eachComputedProperty((name, meta) => {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}).readOnly(),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship(callback, binding) {
get(this, 'relationshipsByName').forEach((relationship, name) => {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType(callback, binding) {
let relationshipTypes = get(this, 'relatedTypes');
for (let i = 0; i < relationshipTypes.length; i++) {
let type = relationshipTypes[i];
callback.call(binding, type);
}
},
determineRelationshipType(knownSide, store) {
let knownKey = knownSide.key;
let knownKind = knownSide.kind;
let inverse = this.inverseFor(knownKey, store);
// let key;
let otherKind;
if (!inverse) {
return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
}
// key = inverse.name;
otherKind = inverse.kind;
if (otherKind === 'belongsTo') {
return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
} else {
return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
}
},
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
let attributes = Ember.get(Person, 'attributes')
attributes.forEach(function(meta, name) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function() {
let map = Map.create();
this.eachComputedProperty((name, meta) => {
if (meta.isAttribute) {
assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');
meta.name = name;
map.set(name, meta);
}
});
return map;
}).readOnly(),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
let transformedAttributes = Ember.get(Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function() {
let map = Map.create();
this.eachAttribute((key, meta) => {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}).readOnly(),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
import DS from 'ember-data';
let Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
@static
*/
eachAttribute(callback, binding) {
get(this, 'attributes').forEach((meta, name) => {
callback.call(binding, name, meta);
});
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a string containing the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
import DS from 'ember-data';
let Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
@static
*/
eachTransformedAttribute(callback, binding) {
get(this, 'transformedAttributes').forEach((type, name) => {
callback.call(binding, name, type);
});
}
});
// if `Ember.setOwner` is defined, accessing `this.container` is
// deprecated (but functional). In "standard" Ember usage, this
// deprecation is actually created via an `.extend` of the factory
// inside the container itself, but that only happens on models
// with MODEL_FACTORY_INJECTIONS enabled :(
if (Ember.setOwner) {
Object.defineProperty(Model.prototype, 'container', {
configurable: true,
enumerable: false,
get() {
deprecate('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.',
false,
{ id: 'ember-application.injected-container', until: '3.0.0' });
return this.store.container;
}
});
}
if (isEnabled('ds-rollback-attribute')) {
Model.reopen({
/**
Discards any unsaved changes to the given attribute. This feature is not enabled by default. You must enable `ds-rollback-attribute` and be running a canary build.
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollbackAttribute('name');
record.get('name'); // 'Untitled Document'
```
@method rollbackAttribute
*/
rollbackAttribute(attributeName) {
if (attributeName in this._internalModel._attributes) {
this.set(attributeName, this._internalModel.lastAcknowledgedValue(attributeName));
}
}
});
}
runInDebug(() => {
Model.reopen({
// This is a temporary solution until we refactor DS.Model to not
// rely on the data property.
willMergeMixin(props) {
let constructor = this.constructor;
assert('`' + intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0]);
assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + constructor.toString(), Object.keys(props).indexOf('id') === -1);
},
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param {Object} proto
@param {String} key
@param {Ember.ComputedProperty} value
*/
didDefineProperty(proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.ComputedProperty) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
let meta = value.meta();
meta.parentType = proto.constructor;
}
}
})
});
export default Model;
| addon/-private/system/model/model.js | import Ember from 'ember';
import { assert, deprecate, warn, runInDebug } from 'ember-data/-debug';
import { PromiseObject } from "../promise-proxies";
import Errors from "../model/errors";
import isEnabled from '../../features';
import RootState from '../model/states';
import {
relationshipsByNameDescriptor,
relatedTypesDescriptor,
relationshipsDescriptor
} from '../relationships/ext';
const {
get,
computed,
Map
} = Ember;
/**
@module ember-data
*/
function findPossibleInverses(type, inverseType, name, relationshipsSoFar) {
let possibleRelationships = relationshipsSoFar || [];
let relationshipMap = get(inverseType, 'relationships');
if (!relationshipMap) { return possibleRelationships; }
let relationships = relationshipMap.get(type.modelName).filter(relationship => {
let optionsForRelationship = inverseType.metaForProperty(relationship.name).options;
if (!optionsForRelationship.inverse) {
return true;
}
return name === optionsForRelationship.inverse;
});
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationships);
}
//Recurse to support polymorphism
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, name, possibleRelationships);
}
return possibleRelationships;
}
function intersection (array1, array2) {
let result = [];
array1.forEach((element) => {
if (array2.indexOf(element) >= 0) {
result.push(element);
}
});
return result;
}
const RESERVED_MODEL_PROPS = [
'currentState', 'data', 'store'
];
const retrieveFromCurrentState = computed('currentState', function(key) {
return get(this._internalModel.currentState, key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
This is the public API of Ember Data models. If you are using Ember Data
in your application, this is the class you should use.
If you are working on Ember Data internals, you most likely want to be dealing
with `InternalModel`
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
const Model = Ember.Object.extend(Ember.Evented, {
_internalModel: null,
store: null,
__defineNonEnumerable(property) {
this[property.name] = property.descriptor.value;
},
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
let record = store.createRecord('model');
record.get('isLoaded'); // true
store.findRecord('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
let record = store.createRecord('model');
record.get('hasDirtyAttributes'); // true
store.findRecord('model', 1).then(function(model) {
model.get('hasDirtyAttributes'); // false
model.set('foo', 'some value');
model.get('hasDirtyAttributes'); // true
});
```
@since 1.13.0
@property hasDirtyAttributes
@type {Boolean}
@readOnly
*/
hasDirtyAttributes: computed('currentState.isDirty', function() {
return this.get('currentState.isDirty');
}),
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
let record = store.createRecord('model');
record.get('isSaving'); // false
let promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`hasDirtyAttributes` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the
change has persisted.
Example
```javascript
let record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('hasDirtyAttributes'); // true
record.get('isSaving'); // false
// Persisting the deletion
let promise = record.save();
record.get('isDeleted'); // true
record.get('isSaving'); // true
// Deletion Persisted
promise.then(function() {
record.get('isDeleted'); // true
record.get('isSaving'); // false
record.get('hasDirtyAttributes'); // false
});
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
let record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state.
A record will be in the `valid` state when the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
let record = store.createRecord('model');
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend for any reason other than a server-side
validation error.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record from the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
let record = store.createRecord('model');
record.get('id'); // null
store.findRecord('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
currentState: RootState.empty,
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
contains keys corresponding to the invalid property names
and values which are arrays of Javascript objects with two keys:
- `message` A string containing the error message from the backend
- `attribute` The name of the property associated with this error message
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
record.get('errors').get('foo');
// [{message: 'foo should be a number.', attribute: 'foo'}]
});
```
The `errors` property us useful for displaying error messages to
the user.
```handlebars
<label>Username: {{input value=username}} </label>
{{#each model.errors.username as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each model.errors.email as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
```
You can also access the special `messages` property on the error
object to get an array of all the error strings.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property errors
@type {DS.Errors}
*/
errors: computed(function() {
let errors = Errors.create();
errors._registerHandlers(this._internalModel,
function() {
this.send('becameInvalid');
},
function() {
this.send('becameValid');
});
return errors;
}).readOnly(),
/**
This property holds the `DS.AdapterError` object with which
last adapter operation was rejected.
@property adapterError
@type {DS.AdapterError}
*/
adapterError: null,
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize(options) {
return this._internalModel.createSnapshot().serialize(options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@return {Object} A JSON representation of the object.
*/
toJSON(options) {
// container is for lazy transform lookups
let serializer = this.store.serializerFor('-default');
let snapshot = this._internalModel.createSnapshot();
return serializer.serialize(snapshot, options);
},
/**
Fired when the record is ready to be interacted with,
that is either loaded from the server or created locally.
@event ready
*/
ready: null,
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: null,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: null,
/**
Fired when a new record is commited to the server.
@event didCreate
*/
didCreate: null,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: null,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: null,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: null,
/**
Fired when the record is rolled back.
@event rolledBack
*/
rolledBack: null,
//TODO Do we want to deprecate these?
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send(name, context) {
return this._internalModel.send(name, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo(name) {
return this._internalModel.transitionTo(name);
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollbackAttributes()`
after a delete was made.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
softDelete: function() {
this.controller.get('model').deleteRecord();
},
confirm: function() {
this.controller.get('model').save();
},
undo: function() {
this.controller.get('model').rollbackAttributes();
}
}
});
```
@method deleteRecord
*/
deleteRecord() {
this._internalModel.deleteRecord();
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
delete: function() {
let controller = this.controller;
controller.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
If you pass an object on the `adapterOptions` property of the options
argument it will be passed to your adapter via the snapshot
```js
record.destroyRecord({ adapterOptions: { subscribe: false } });
```
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default MyCustomAdapter.extend({
deleteRecord: function(store, type, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
});
```
@method destroyRecord
@param {Object} options
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord(options) {
this.deleteRecord();
return this.save(options);
},
/**
Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection.
@method unloadRecord
*/
unloadRecord() {
if (this.isDestroyed) { return; }
this._internalModel.unloadRecord();
},
/**
@method _notifyProperties
@private
*/
_notifyProperties(keys) {
Ember.beginPropertyChanges();
let key;
for (let i = 0, length = keys.length; i < length; i++) {
key = keys[i];
this.notifyPropertyChange(key);
}
Ember.endPropertyChanges();
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
The array represents the diff of the canonical state with the local state
of the model. Note: if the model is created locally, the canonical state is
empty since the adapter hasn't acknowledged the attributes yet:
Example
```app/models/mascot.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
isAdmin: DS.attr('boolean', {
defaultValue: false
})
});
```
```javascript
let mascot = store.createRecord('mascot');
mascot.changedAttributes(); // {}
mascot.set('name', 'Tomster');
mascot.changedAttributes(); // { name: [undefined, 'Tomster'] }
mascot.set('isAdmin', true);
mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] }
mascot.save().then(function() {
mascot.changedAttributes(); // {}
mascot.set('isAdmin', false);
mascot.changedAttributes(); // { isAdmin: [true, false] }
});
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes() {
return this._internalModel.changedAttributes();
},
//TODO discuss with tomhuda about events/hooks
//Bring back as hooks?
/**
@method adapterWillCommit
@private
adapterWillCommit: function() {
this.send('willCommit');
},
/**
@method adapterDidDirty
@private
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
*/
/**
If the model `hasDirtyAttributes` this function will discard any unsaved
changes. If the model `isNew` it will be removed from the store.
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollbackAttributes();
record.get('name'); // 'Untitled Document'
```
@since 1.13.0
@method rollbackAttributes
*/
rollbackAttributes() {
this._internalModel.rollbackAttributes();
},
/*
@method _createSnapshot
@private
*/
_createSnapshot() {
return this._internalModel.createSnapshot();
},
toStringExtension() {
return get(this, 'id');
},
/**
Save the record and persist any changes to the record to an
external source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function() {
// Success callback
}, function() {
// Error callback
});
```
If you pass an object on the `adapterOptions` property of the options
argument it will be passed to you adapter via the snapshot
```js
record.save({ adapterOptions: { subscribe: false } });
```
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default MyCustomAdapter.extend({
updateRecord: function(store, type, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
});
```
@method save
@param {Object} options
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save(options) {
return PromiseObject.create({
promise: this._internalModel.save(options).then(() => this)
});
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading.
Example
```app/routes/model/view.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
reload: function() {
this.controller.get('model').reload().then(function(model) {
// do something with the reloaded model
});
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload() {
return PromiseObject.create({
promise: this._internalModel.reload().then(() => this)
});
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param {String} name
*/
trigger(name) {
let fn = this[name];
if (typeof fn === 'function') {
let length = arguments.length;
let args = new Array(length - 1);
for (let i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
fn.apply(this, args)
}
this._super(...arguments);
},
attr() {
assert("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false);
},
/**
Get the reference for the specified belongsTo relationship.
Example
```app/models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
```
```javascript
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
// check if the user relationship is loaded
let isLoaded = userRef.value() !== null;
// get the record of the reference (null if not yet available)
let user = userRef.value();
// get the identifier of the reference
if (userRef.remoteType() === "id") {
let id = userRef.id();
} else if (userRef.remoteType() === "link") {
let link = userRef.link();
}
// load user (via store.findRecord or store.findBelongsTo)
userRef.load().then(...)
// or trigger a reload
userRef.reload().then(...)
// provide data for reference
userRef.push({
type: 'user',
id: 1,
attributes: {
username: "@user"
}
}).then(function(user) {
userRef.value() === user;
});
```
@method belongsTo
@param {String} name of the relationship
@since 2.5.0
@return {BelongsToReference} reference for this relationship
*/
belongsTo(name) {
return this._internalModel.referenceFor('belongsTo', name);
},
/**
Get the reference for the specified hasMany relationship.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
comments: {
data: [
{ type: 'comment', id: 1 },
{ type: 'comment', id: 2 }
]
}
}
}
});
let commentsRef = blog.hasMany('comments');
// check if the comments are loaded already
let isLoaded = commentsRef.value() !== null;
// get the records of the reference (null if not yet available)
let comments = commentsRef.value();
// get the identifier of the reference
if (commentsRef.remoteType() === "ids") {
let ids = commentsRef.ids();
} else if (commentsRef.remoteType() === "link") {
let link = commentsRef.link();
}
// load comments (via store.findMany or store.findHasMany)
commentsRef.load().then(...)
// or trigger a reload
commentsRef.reload().then(...)
// provide data for reference
commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) {
commentsRef.value() === comments;
});
```
@method hasMany
@param {String} name of the relationship
@since 2.5.0
@return {HasManyReference} reference for this relationship
*/
hasMany(name) {
return this._internalModel.referenceFor('hasMany', name);
},
setId: Ember.observer('id', function () {
this._internalModel.setId(this.get('id'));
}),
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo() {
let attributes = ['id'];
let relationships = { };
let expensiveProperties = [];
this.eachAttribute((name, meta) => attributes.push(name));
let groups = [
{
name: 'Attributes',
properties: attributes,
expand: true
}
];
this.eachRelationship((name, relationship) => {
let properties = relationships[relationship.kind];
if (properties === undefined) {
properties = relationships[relationship.kind] = [];
groups.push({
name: relationship.name,
properties,
expand: true
});
}
properties.push(name);
expensiveProperties.push(name);
});
groups.push({
name: 'Flags',
properties: ['isLoaded', 'hasDirtyAttributes', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
});
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
},
notifyBelongsToChanged(key) {
this.notifyPropertyChange(key);
},
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, descriptor);
```
- `name` the name of the current property in the iteration
- `descriptor` the meta object that describes this relationship
The relationship descriptor argument is an object with the following properties.
- **key** <span class="type">String</span> the name of this relationship on the Model
- **kind** <span class="type">String</span> "hasMany" or "belongsTo"
- **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
- **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship
- **type** <span class="type">String</span> the type name of the related Model
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(record, options) {
let json = {};
record.eachRelationship(function(name, descriptor) {
if (descriptor.kind === 'hasMany') {
let serializedHasManyName = name.toUpperCase() + '_IDS';
json[serializedHasManyName] = record.get(name).mapBy('id');
}
});
return json;
}
});
```
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship(callback, binding) {
this.constructor.eachRelationship(callback, binding);
},
relationshipFor(name) {
return get(this.constructor, 'relationshipsByName').get(name);
},
inverseFor(key) {
return this.constructor.inverseFor(key, this.store);
},
notifyHasManyAdded(key) {
//We need to notifyPropertyChange in the adding case because we need to make sure
//we fetch the newly added record in case it is unloaded
//TODO(Igor): Consider whether we could do this only if the record state is unloaded
//Goes away once hasMany is double promisified
this.notifyPropertyChange(key);
},
eachAttribute(callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
/**
@property data
@private
@type {Object}
*/
Object.defineProperty(Model.prototype, 'data', {
get() {
return this._internalModel._data;
}
});
runInDebug(function() {
Model.reopen({
init() {
this._super(...arguments);
if (!this._internalModel) {
throw new Ember.Error('You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.');
}
}
});
});
Model.reopenClass({
isModel: true,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
/**
Represents the model's class name as a string. This can be used to look up the model's class name through
`DS.Store`'s modelFor method.
`modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string.
For example:
```javascript
store.modelFor('post').modelName; // 'post'
store.modelFor('blog-post').modelName; // 'blog-post'
```
The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
keys to underscore (instead of dasherized), you might use the following code:
```javascript
export default const PostSerializer = DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.underscore(modelName);
}
});
```
@property modelName
@type String
@readonly
@static
*/
modelName: null,
/*
These class methods below provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `store.modelFor('post').typeForRelationship('comments', store)` will return `Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@param {store} store an instance of DS.Store
@return {DS.Model} the type of the relationship, or undefined
*/
typeForRelationship(name, store) {
let relationship = get(this, 'relationshipsByName').get(name);
return relationship && store.modelFor(relationship.type);
},
inverseMap: Ember.computed(function() {
return Object.create(null);
}),
/**
Find the relationship which is the inverse of the one asked for.
For example, if you define models like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('message')
});
```
```app/models/message.js
import DS from 'ember-data';
export default DS.Model.extend({
owner: DS.belongsTo('post')
});
```
``` js
store.modelFor('post').inverseFor('comments', store) // { type: App.Message, name: 'owner', kind: 'belongsTo' }
store.modelFor('message').inverseFor('owner', store) // { type: App.Post, name: 'comments', kind: 'hasMany' }
```
@method inverseFor
@static
@param {String} name the name of the relationship
@param {DS.Store} store
@return {Object} the inverse relationship, or null
*/
inverseFor(name, store) {
let inverseMap = get(this, 'inverseMap');
if (inverseMap[name] !== undefined) {
return inverseMap[name];
} else {
let relationship = get(this, 'relationshipsByName').get(name);
if (!relationship) {
inverseMap[name] = null;
return null;
}
let options = relationship.options;
if (options && options.inverse === null) {
// populate the cache with a miss entry so we can skip getting and going
// through `relationshipsByName`
inverseMap[name] = null;
return null;
}
return inverseMap[name] = this._findInverseFor(name, store);
}
},
//Calculate the inverse, ignoring the cache
_findInverseFor(name, store) {
let inverseType = this.typeForRelationship(name, store);
if (!inverseType) {
return null;
}
let propertyMeta = this.metaForProperty(name);
//If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })`
let options = propertyMeta.options;
if (options.inverse === null) { return null; }
let inverseName, inverseKind, inverse;
//If inverse is specified manually, return the inverse
if (options.inverse) {
inverseName = options.inverse;
inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName);
assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.modelName +
"' model. This is most likely due to a missing attribute on your model definition.", !Ember.isNone(inverse));
inverseKind = inverse.kind;
} else {
//No inverse was specified manually, we need to use a heuristic to guess one
if (propertyMeta.parentType && propertyMeta.type === propertyMeta.parentType.modelName) {
warn(`Detected a reflexive relationship by the name of '${name}' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.`, false, {
id: 'ds.model.reflexive-relationship-without-inverse'
});
}
let possibleRelationships = findPossibleInverses(this, inverseType, name);
if (possibleRelationships.length === 0) { return null; }
let filteredRelationships = possibleRelationships.filter((possibleRelationship) => {
let optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options;
return name === optionsForRelationship.inverse;
});
assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " +
inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
filteredRelationships.length < 2);
if (filteredRelationships.length === 1 ) {
possibleRelationships = filteredRelationships;
}
assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " +
this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses",
possibleRelationships.length === 1);
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
import User from 'app/models/user';
import Post from 'app/models/post';
let relationships = Ember.get(Blog, 'relationships');
relationships.get(User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: relationshipsDescriptor,
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relationshipNames = Ember.get(Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function() {
let names = {
hasMany: [],
belongsTo: []
};
this.eachComputedProperty((name, meta) => {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relatedTypes = Ember.get(Blog, 'relatedTypes');
//=> [ User, Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: relatedTypesDescriptor,
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relationshipsByName = Ember.get(Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: relationshipsByNameDescriptor,
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
```
```js
import Ember from 'ember';
import Blog from 'app/models/blog';
let fields = Ember.get(Blog, 'fields');
fields.forEach(function(kind, field) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function() {
let map = Map.create();
this.eachComputedProperty((name, meta) => {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}).readOnly(),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship(callback, binding) {
get(this, 'relationshipsByName').forEach((relationship, name) => {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType(callback, binding) {
let relationshipTypes = get(this, 'relatedTypes');
for (let i = 0; i < relationshipTypes.length; i++) {
let type = relationshipTypes[i];
callback.call(binding, type);
}
},
determineRelationshipType(knownSide, store) {
let knownKey = knownSide.key;
let knownKind = knownSide.kind;
let inverse = this.inverseFor(knownKey, store);
// let key;
let otherKind;
if (!inverse) {
return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
}
// key = inverse.name;
otherKind = inverse.kind;
if (otherKind === 'belongsTo') {
return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
} else {
return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
}
},
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
let attributes = Ember.get(Person, 'attributes')
attributes.forEach(function(meta, name) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function() {
let map = Map.create();
this.eachComputedProperty((name, meta) => {
if (meta.isAttribute) {
assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');
meta.name = name;
map.set(name, meta);
}
});
return map;
}).readOnly(),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
let transformedAttributes = Ember.get(Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function() {
let map = Map.create();
this.eachAttribute((key, meta) => {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}).readOnly(),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
import DS from 'ember-data';
let Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
@static
*/
eachAttribute(callback, binding) {
get(this, 'attributes').forEach((meta, name) => {
callback.call(binding, name, meta);
});
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a string containing the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
import DS from 'ember-data';
let Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
@static
*/
eachTransformedAttribute(callback, binding) {
get(this, 'transformedAttributes').forEach((type, name) => {
callback.call(binding, name, type);
});
}
});
// if `Ember.setOwner` is defined, accessing `this.container` is
// deprecated (but functional). In "standard" Ember usage, this
// deprecation is actually created via an `.extend` of the factory
// inside the container itself, but that only happens on models
// with MODEL_FACTORY_INJECTIONS enabled :(
if (Ember.setOwner) {
Object.defineProperty(Model.prototype, 'container', {
configurable: true,
enumerable: false,
get() {
deprecate('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.',
false,
{ id: 'ember-application.injected-container', until: '3.0.0' });
return this.store.container;
}
});
}
if (isEnabled('ds-rollback-attribute')) {
Model.reopen({
/**
Discards any unsaved changes to the given attribute. This feature is not enabled by default. You must enable `ds-rollback-attribute` and be running a canary build.
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollbackAttribute('name');
record.get('name'); // 'Untitled Document'
```
@method rollbackAttribute
*/
rollbackAttribute(attributeName) {
if (attributeName in this._internalModel._attributes) {
this.set(attributeName, this._internalModel.lastAcknowledgedValue(attributeName));
}
}
});
}
runInDebug(() => {
Model.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param {Object} proto
@param {String} key
@param {Ember.ComputedProperty} value
*/
didDefineProperty(proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.ComputedProperty) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
let meta = value.meta();
meta.parentType = proto.constructor;
}
}
})
});
export default Model;
| tidy up spacing | addon/-private/system/model/model.js | tidy up spacing | <ide><path>ddon/-private/system/model/model.js
<ide>
<ide> runInDebug(() => {
<ide> Model.reopen({
<del> /**
<del> This Ember.js hook allows an object to be notified when a property
<del> is defined.
<del>
<del> In this case, we use it to be notified when an Ember Data user defines a
<del> belongs-to relationship. In that case, we need to set up observers for
<del> each one, allowing us to track relationship changes and automatically
<del> reflect changes in the inverse has-many array.
<del>
<del> This hook passes the class being set up, as well as the key and value
<del> being defined. So, for example, when the user does this:
<del>
<del> ```javascript
<del> DS.Model.extend({
<del> parent: DS.belongsTo('user')
<del> });
<del> ```
<del>
<del> This hook would be called with "parent" as the key and the computed
<del> property returned by `DS.belongsTo` as the value.
<del>
<del> @method didDefineProperty
<del> @param {Object} proto
<del> @param {String} key
<del> @param {Ember.ComputedProperty} value
<del> */
<add> // This is a temporary solution until we refactor DS.Model to not
<add> // rely on the data property.
<add> willMergeMixin(props) {
<add> let constructor = this.constructor;
<add> assert('`' + intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0]);
<add> assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + constructor.toString(), Object.keys(props).indexOf('id') === -1);
<add> },
<add>
<add> /**
<add> This Ember.js hook allows an object to be notified when a property
<add> is defined.
<add>
<add> In this case, we use it to be notified when an Ember Data user defines a
<add> belongs-to relationship. In that case, we need to set up observers for
<add> each one, allowing us to track relationship changes and automatically
<add> reflect changes in the inverse has-many array.
<add>
<add> This hook passes the class being set up, as well as the key and value
<add> being defined. So, for example, when the user does this:
<add>
<add> ```javascript
<add> DS.Model.extend({
<add> parent: DS.belongsTo('user')
<add> });
<add> ```
<add>
<add> This hook would be called with "parent" as the key and the computed
<add> property returned by `DS.belongsTo` as the value.
<add>
<add> @method didDefineProperty
<add> @param {Object} proto
<add> @param {String} key
<add> @param {Ember.ComputedProperty} value
<add> */
<ide> didDefineProperty(proto, key, value) {
<ide> // Check if the value being set is a computed property.
<ide> if (value instanceof Ember.ComputedProperty) { |
|
JavaScript | agpl-3.0 | fda80e0c2c953148292b35839ff368ff92c56baf | 0 | jmoenig/Snap--Build-Your-Own-Blocks,jmoenig/Snap--Build-Your-Own-Blocks | /*
gui.js
a programming environment
based on morphic.js, blocks.js, threads.js and objects.js
inspired by Scratch
written by Jens Mönig
[email protected]
Copyright (C) 2020 by Jens Mönig
This file is part of Snap!.
Snap! is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
prerequisites:
--------------
needs blocks.js, threads.js, objects.js, cloud.jus and morphic.js
toc
---
the following list shows the order in which all constructors are
defined. Use this list to locate code in this document:
IDE_Morph
ProjectDialogMorph
SpriteIconMorph
TurtleIconMorph
CostumeIconMorph
WardrobeMorph
StageHandleMorph
PaletteHandleMorph
CamSnapshotDialogMorph
SoundRecorderDialogMorph
credits
-------
Nathan Dinsmore contributed saving and loading of projects,
ypr-Snap! project conversion and countless bugfixes
Ian Reynolds contributed handling and visualization of sounds
Michael Ball contributed the LibraryImportDialogMorph and countless
utilities to load libraries from relative urls
Bernat Romagosa contributed more things than I can mention,
including interfacing to the camera and microphone
*/
/*global modules, Morph, SpriteMorph, SyntaxElementMorph, Color, Cloud, Audio,
ListWatcherMorph, TextMorph, newCanvas, useBlurredShadows, VariableFrame, Sound,
StringMorph, Point, MenuMorph, morphicVersion, DialogBoxMorph, normalizeCanvas,
ToggleButtonMorph, contains, ScrollFrameMorph, StageMorph, PushButtonMorph, sb,
InputFieldMorph, FrameMorph, Process, nop, SnapSerializer, ListMorph, detect,
AlignmentMorph, TabMorph, Costume, MorphicPreferences,BlockMorph, ToggleMorph,
InputSlotDialogMorph, ScriptsMorph, isNil, SymbolMorph, fontHeight, localize,
BlockExportDialogMorph, BlockImportDialogMorph, SnapTranslator, List, ArgMorph,
Uint8Array, HandleMorph, SVG_Costume, TableDialogMorph, CommentMorph, saveAs,
CommandBlockMorph, BooleanSlotMorph, RingReporterSlotMorph, ScriptFocusMorph,
BlockLabelPlaceHolderMorph, SpeechBubbleMorph, XML_Element, WatcherMorph,
BlockRemovalDialogMorph,TableMorph, isSnapObject, isRetinaEnabled, SliderMorph,
disableRetinaSupport, enableRetinaSupport, isRetinaSupported, MediaRecorder,
Animation, BoxMorph, BlockEditorMorph, BlockDialogMorph, Note*/
// Global stuff ////////////////////////////////////////////////////////
modules.gui = '2020-April-30';
// Declarations
var IDE_Morph;
var ProjectDialogMorph;
var LibraryImportDialogMorph;
var SpriteIconMorph;
var CostumeIconMorph;
var TurtleIconMorph;
var WardrobeMorph;
var SoundIconMorph;
var JukeboxMorph;
var StageHandleMorph;
var PaletteHandleMorph;
var CamSnapshotDialogMorph;
var SoundRecorderDialogMorph;
// IDE_Morph ///////////////////////////////////////////////////////////
// I am SNAP's top-level frame, the Editor window
// IDE_Morph inherits from Morph:
IDE_Morph.prototype = new Morph();
IDE_Morph.prototype.constructor = IDE_Morph;
IDE_Morph.uber = Morph.prototype;
// IDE_Morph preferences settings and skins
IDE_Morph.prototype.setDefaultDesign = function () {
MorphicPreferences.isFlat = false;
SpriteMorph.prototype.paletteColor = new Color(55, 55, 55);
SpriteMorph.prototype.paletteTextColor = new Color(230, 230, 230);
StageMorph.prototype.paletteTextColor
= SpriteMorph.prototype.paletteTextColor;
StageMorph.prototype.paletteColor = SpriteMorph.prototype.paletteColor;
SpriteMorph.prototype.sliderColor
= SpriteMorph.prototype.paletteColor.lighter(30);
IDE_Morph.prototype.buttonContrast = 30;
IDE_Morph.prototype.backgroundColor = new Color(40, 40, 40);
IDE_Morph.prototype.frameColor = SpriteMorph.prototype.paletteColor;
IDE_Morph.prototype.groupColor
= SpriteMorph.prototype.paletteColor.lighter(8);
IDE_Morph.prototype.sliderColor = SpriteMorph.prototype.sliderColor;
IDE_Morph.prototype.buttonLabelColor = new Color(255, 255, 255);
IDE_Morph.prototype.tabColors = [
IDE_Morph.prototype.groupColor.darker(40),
IDE_Morph.prototype.groupColor.darker(60),
IDE_Morph.prototype.groupColor
];
IDE_Morph.prototype.rotationStyleColors = IDE_Morph.prototype.tabColors;
IDE_Morph.prototype.appModeColor = new Color();
IDE_Morph.prototype.scriptsPaneTexture = this.scriptsTexture();
IDE_Morph.prototype.padding = 5;
SpriteIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
CostumeIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
SoundIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
TurtleIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
SyntaxElementMorph.prototype.contrast = 65;
ScriptsMorph.prototype.feedbackColor = new Color(255, 255, 255);
};
IDE_Morph.prototype.setFlatDesign = function () {
MorphicPreferences.isFlat = true;
SpriteMorph.prototype.paletteColor = new Color(255, 255, 255);
SpriteMorph.prototype.paletteTextColor = new Color(70, 70, 70);
StageMorph.prototype.paletteTextColor
= SpriteMorph.prototype.paletteTextColor;
StageMorph.prototype.paletteColor = SpriteMorph.prototype.paletteColor;
SpriteMorph.prototype.sliderColor = SpriteMorph.prototype.paletteColor;
IDE_Morph.prototype.buttonContrast = 30;
IDE_Morph.prototype.backgroundColor = new Color(220, 220, 230);
IDE_Morph.prototype.frameColor = new Color(240, 240, 245);
IDE_Morph.prototype.groupColor = new Color(255, 255, 255);
IDE_Morph.prototype.sliderColor = SpriteMorph.prototype.sliderColor;
IDE_Morph.prototype.buttonLabelColor = new Color(70, 70, 70);
IDE_Morph.prototype.tabColors = [
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor.lighter(50),
IDE_Morph.prototype.groupColor
];
IDE_Morph.prototype.rotationStyleColors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.groupColor.darker(10),
IDE_Morph.prototype.groupColor.darker(30)
];
IDE_Morph.prototype.appModeColor = IDE_Morph.prototype.frameColor;
IDE_Morph.prototype.scriptsPaneTexture = null;
IDE_Morph.prototype.padding = 1;
SpriteIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
CostumeIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
SoundIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
TurtleIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
SyntaxElementMorph.prototype.contrast = 25;
ScriptsMorph.prototype.feedbackColor = new Color(153, 255, 213);
};
IDE_Morph.prototype.scriptsTexture = function () {
var pic = newCanvas(new Point(100, 100)), // bigger scales faster
ctx = pic.getContext('2d'),
i;
for (i = 0; i < 100; i += 4) {
ctx.fillStyle = this.frameColor.toString();
ctx.fillRect(i, 0, 1, 100);
ctx.fillStyle = this.groupColor.lighter(6).toString();
ctx.fillRect(i + 1, 0, 1, 100);
ctx.fillRect(i + 3, 0, 1, 100);
ctx.fillStyle = this.groupColor.toString();
ctx.fillRect(i + 2, 0, 1, 100);
}
return pic;
};
IDE_Morph.prototype.setDefaultDesign();
// IDE_Morph instance creation:
function IDE_Morph(isAutoFill) {
this.init(isAutoFill);
}
IDE_Morph.prototype.init = function (isAutoFill) {
// global font setting
MorphicPreferences.globalFontFamily = 'Helvetica, Arial';
// restore saved user preferences
this.userLanguage = null; // user language preference for startup
this.projectsInURLs = false;
this.applySavedSettings();
// additional properties:
this.cloud = new Cloud();
this.cloudMsg = null;
this.source = null;
this.serializer = new SnapSerializer();
this.globalVariables = new VariableFrame();
this.currentSprite = new SpriteMorph(this.globalVariables);
this.sprites = new List([this.currentSprite]);
this.currentCategory = 'motion';
this.currentTab = 'scripts';
this.projectName = '';
this.projectNotes = '';
// logoURL is disabled because the image data is hard-copied
// to avoid tainting the world canvas
// this.logoURL = this.resourceURL('src', 'snap_logo_sm.png');
this.logo = null;
this.controlBar = null;
this.categories = null;
this.palette = null;
this.paletteHandle = null;
this.spriteBar = null;
this.spriteEditor = null;
this.stage = null;
this.stageHandle = null;
this.corralBar = null;
this.corral = null;
this.embedPlayButton = null;
this.embedOverlay = null;
this.isEmbedMode = false;
this.isAutoFill = isAutoFill === undefined ? true : isAutoFill;
this.isAppMode = false;
this.isSmallStage = false;
this.filePicker = null;
this.hasChangedMedia = false;
this.isAnimating = true;
this.paletteWidth = 200; // initially same as logo width
this.stageRatio = 1; // for IDE animations, e.g. when zooming
this.wasSingleStepping = false; // for toggling to and from app mode
this.loadNewProject = false; // flag when starting up translated
this.shield = null;
this.savingPreferences = true; // for bh's infamous "Eisenbergification"
// initialize inherited properties:
IDE_Morph.uber.init.call(this);
// override inherited properites:
this.color = this.backgroundColor;
};
IDE_Morph.prototype.openIn = function (world) {
var hash, myself = this, urlLanguage = null;
function initUser(username) {
sessionStorage.username = username;
if (username) {
myself.source = 'cloud';
if (!myself.cloud.verified) {
new DialogBoxMorph().inform(
'Unverified account',
'Your account is still unverified.\n' +
'Please use the verification link that\n' +
'was sent to your email address when you\n' +
'signed up.\n\n' +
'If you cannot find that email, please\n' +
'check your spam folder. If you still\n' +
'cannot find it, please use the "Resend\n' +
'Verification Email..." option in the cloud\n' +
'menu.',
world,
myself.cloudIcon(null, new Color(0, 180, 0))
);
}
}
}
if (location.protocol !== 'file:') {
if (!sessionStorage.username) {
// check whether login should persist across browser sessions
this.cloud.initSession(initUser);
} else {
// login only persistent during a single browser session
this.cloud.checkCredentials(initUser);
}
}
this.buildPanes();
world.add(this);
world.userMenu = this.userMenu;
// override SnapCloud's user message with Morphic
this.cloud.message = (string) => {
var m = new MenuMorph(null, string),
intervalHandle;
m.popUpCenteredInWorld(world);
intervalHandle = setInterval(() => {
m.destroy();
clearInterval(intervalHandle);
}, 2000);
};
// prevent non-DialogBoxMorphs from being dropped
// onto the World in user-mode
world.reactToDropOf = (morph) => {
if (!(morph instanceof DialogBoxMorph ||
(morph instanceof MenuMorph))) {
if (world.hand.grabOrigin) {
morph.slideBackTo(world.hand.grabOrigin);
} else {
world.hand.grab(morph);
}
}
};
this.reactToWorldResize(world.bounds);
function getURL(url) {
try {
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send();
if (request.status === 200) {
return request.responseText;
}
throw new Error('unable to retrieve ' + url);
} catch (err) {
myself.showMessage('unable to retrieve project');
return '';
}
}
function applyFlags(dict) {
if (dict.embedMode) {
myself.setEmbedMode();
}
if (dict.editMode) {
myself.toggleAppMode(false);
} else {
myself.toggleAppMode(true);
}
if (!dict.noRun) {
myself.runScripts();
}
if (dict.hideControls) {
myself.controlBar.hide();
window.onbeforeunload = nop;
}
if (dict.noExitWarning) {
window.onbeforeunload = nop;
}
if (dict.lang) {
myself.setLanguage(dict.lang, null, true); // don't persist
}
// only force my world to get focus if I'm not in embed mode
// to prevent the iFrame from involuntarily scrolling into view
if (!myself.isEmbedMode) {
world.worldCanvas.focus();
}
}
// dynamic notifications from non-source text files
// has some issues, commented out for now
/*
this.cloudMsg = getURL('https://snap.berkeley.edu/cloudmsg.txt');
motd = getURL('https://snap.berkeley.edu/motd.txt');
if (motd) {
this.inform('Snap!', motd);
}
*/
function interpretUrlAnchors() {
var dict, idx;
if (location.hash.substr(0, 6) === '#open:') {
hash = location.hash.substr(6);
if (hash.charAt(0) === '%'
|| hash.search(/\%(?:[0-9a-f]{2})/i) > -1) {
hash = decodeURIComponent(hash);
}
if (contains(
['project', 'blocks', 'sprites', 'snapdata'].map(each =>
hash.substr(0, 8).indexOf(each)
),
1
)) {
this.droppedText(hash);
} else {
idx = hash.indexOf("&");
if (idx > 0) {
dict = myself.cloud.parseDict(hash.substr(idx));
dict.editMode = true;
hash = hash.slice(0, idx);
applyFlags(dict);
}
this.droppedText(getURL(hash));
}
} else if (location.hash.substr(0, 5) === '#run:') {
hash = location.hash.substr(5);
idx = hash.indexOf("&");
if (idx > 0) {
hash = hash.slice(0, idx);
}
if (hash.charAt(0) === '%'
|| hash.search(/\%(?:[0-9a-f]{2})/i) > -1) {
hash = decodeURIComponent(hash);
}
if (hash.substr(0, 8) === '<project>') {
this.rawOpenProjectString(hash);
} else {
this.rawOpenProjectString(getURL(hash));
}
applyFlags(myself.cloud.parseDict(location.hash.substr(5)));
} else if (location.hash.substr(0, 9) === '#present:') {
this.shield = new Morph();
this.shield.color = this.color;
this.shield.setExtent(this.parent.extent());
this.parent.add(this.shield);
myself.showMessage('Fetching project\nfrom the cloud...');
// make sure to lowercase the username
dict = myself.cloud.parseDict(location.hash.substr(9));
dict.Username = dict.Username.toLowerCase();
myself.cloud.getPublicProject(
dict.ProjectName,
dict.Username,
projectData => {
var msg;
myself.nextSteps([
() => msg = myself.showMessage('Opening project...'),
() => {
if (projectData.indexOf('<snapdata') === 0) {
myself.rawOpenCloudDataString(projectData);
} else if (
projectData.indexOf('<project') === 0
) {
myself.rawOpenProjectString(projectData);
}
myself.hasChangedMedia = true;
},
() => {
myself.shield.destroy();
myself.shield = null;
msg.destroy();
applyFlags(dict);
}
]);
},
this.cloudError()
);
} else if (location.hash.substr(0, 7) === '#cloud:') {
this.shield = new Morph();
this.shield.alpha = 0;
this.shield.setExtent(this.parent.extent());
this.parent.add(this.shield);
myself.showMessage('Fetching project\nfrom the cloud...');
// make sure to lowercase the username
dict = myself.cloud.parseDict(location.hash.substr(7));
myself.cloud.getPublicProject(
dict.ProjectName,
dict.Username,
projectData => {
var msg;
myself.nextSteps([
() => msg = myself.showMessage('Opening project...'),
() => {
if (projectData.indexOf('<snapdata') === 0) {
myself.rawOpenCloudDataString(projectData);
} else if (
projectData.indexOf('<project') === 0
) {
myself.rawOpenProjectString(projectData);
}
myself.hasChangedMedia = true;
},
() => {
myself.shield.destroy();
myself.shield = null;
msg.destroy();
myself.toggleAppMode(false);
}
]);
},
this.cloudError()
);
} else if (location.hash.substr(0, 4) === '#dl:') {
myself.showMessage('Fetching project\nfrom the cloud...');
// make sure to lowercase the username
dict = myself.cloud.parseDict(location.hash.substr(4));
dict.Username = dict.Username.toLowerCase();
myself.cloud.getPublicProject(
dict.ProjectName,
dict.Username,
projectData => {
myself.saveXMLAs(projectData, dict.ProjectName);
myself.showMessage(
'Saved project\n' + dict.ProjectName,
2
);
},
this.cloudError()
);
} else if (location.hash.substr(0, 6) === '#lang:') {
urlLanguage = location.hash.substr(6);
this.setLanguage(urlLanguage, null, true); // don't persist
this.loadNewProject = true;
} else if (location.hash.substr(0, 7) === '#signup') {
this.createCloudAccount();
}
this.loadNewProject = false;
}
if (this.userLanguage) {
this.loadNewProject = true;
this.setLanguage(this.userLanguage, interpretUrlAnchors);
} else {
interpretUrlAnchors.call(this);
}
world.keyboardFocus = this.stage;
this.warnAboutIE();
};
// IDE_Morph construction
IDE_Morph.prototype.buildPanes = function () {
this.createLogo();
this.createControlBar();
this.createCategories();
this.createPalette();
this.createStage();
this.createSpriteBar();
this.createSpriteEditor();
this.createCorralBar();
this.createCorral();
};
IDE_Morph.prototype.createLogo = function () {
var myself = this;
if (this.logo) {
this.logo.destroy();
}
this.logo = new Morph();
// the logo texture is not loaded dynamically as an image, but instead
// hard-copied here to avoid tainting the world canvas. This lets us
// use Snap's (and Morphic's) color pickers to sense any pixel which
// otherwise would be compromised by annoying browser security.
// this.logo.texture = this.logoURL; // original code, commented out
this.logo.texture = "data:image/png;base64," +
"iVBORw0KGgoAAAANSUhEUgAAACwAAAAYCAYAAACBbx+6AAAKiklEQVRYR5VXe3BU5RX/" +
"ne+7924SwiOEJJvwUCAgCZFBEtRatIlVlATLIwlFsCgdeYWICu1MfbKUabVVtBoDQlUc" +
"FCubEIpAAEUTrGhFGIXAAjZCFdhNQiTkQbK7997vdO7SREAo9P5zZ77HOb9zzu87D8JV" +
"fOyBwGIwEdg5XrcmKRExcoSCNQKgWwXRTYKQDAKUQi1DbASrjzgsdqdM8zc6d6o80LIB" +
"RR6oq1B52SN0pcteL+SUKbCdcw3lCUMsof2amAs0iVRNEoIhZYKoCcTtYBARxUUZ1IMZ" +
"CIZxWDG9oVSv1/tP8Z12ZHAVNMqBdSW9l9uPAGYGoQwicqjQUQsmZ9kLSf8FGyhzzyCB" +
"P8X1kO7TLaoREJuIxCeSzKNhWzRbKhgyRCwJZfcA2UOY+E4QTewZK2Ob2tQhIl6cPLmu" +
"LKLPC+n8O2X/P+CJAXLAXXzpfLD+sqRHesaKF5vbHZtil4bCA98YeO+2f19J0Yl3+wzV" +
"DH0GMz8cE0WxHSH8DZrxhPsX3x7rBO5YUFgI1Um3y8r0sCg8WOZgBQ54YPTJGNCPgehw" +
"qNl/zfTmJoe3Dt9OeN15LgObTUs/JNB9prvA9/mljNvblCkyh+7l6p3AxVxt2JiQalty" +
"IYB5AL5n5qWh1vqVA2cieCWjz+07AXd8C+eZAP71SY8Q6JlzfuajDPFMSkHg7brtSd1w" +
"Vr2hVIymxX97f2IO2nCPP2be0EDaWZuMVttoP2tGBd5/dfCpToHnKMZUvWSJzP5ZNSin" +
"uouv9RXX/MRW9lMgHkekaqCsVZDmZnfD4JMI7LXPPUgHXATaBVEvLDrg7tBgRDbrK9wz" +
"GHwnM0Xrmsg3bT4eC5XV2FzfYnS/fkzK9zU7aQ7MXxbvnxkk8UhYUTcGTGJyMsM/Okw5" +
"s3rVdY2Zs/foe1MyIw8UHjA8oCosEUA1cjw/AA94M/KUMOcQBW8gsptYuXYpa8Cr/aZW" +
"7Sss9Mrhw33swWJkV1eL6uoc6wFPVVRDo3stmDN/xOFAed95EHYps7o/Jb/hrc6QTXt0" +
"/4QzYa1Egd7TyCq3WEgBGkggMyGhbt2bnpyrDO8PJDizAYPbbS21Tw+rXk+BjzIQvhRF" +
"8ub6MlhiF4h6dKU1J1M4xD+xvnc/CaMKpN5LntywqHM9d77vrwCNrCxNG32x0Oxs1lzp" +
"vmtdQVnfe0DArGvsczNskUAaareWDP/SOT+2qKa/DkrtLu14k8HrW+JrsKbf1xFZN3ES" +
"khrbJ7tPxYYMMRpsxQi4ajaVDjnobI8vrslWLLc6186lNYBqX041hiyoDR339ovWNGs7" +
"GA3J+XUFneDGFft+T4zfCsYDm5enrzsfdF7R12lM1jsAfcPgNmJkMqE3AfEMWqYTlVpK" +
"vcDAbSCcEUCcIO6jSyzWSW04a8rXmGAw4yQYg5nQkxi9GHhu6/L0pbnzfbcxoZIUFXd5" +
"2KlEOR5Yfm/cACFduxnCl5zvv70TWN68/YNYauVSi77BNjs2CmDVQKF/WFIyJPTzh48m" +
"GVbwCwK6E+MJJtpBLKUi+1kC3wNShbaF40KDrkM7FrQ0S5PmsyCMd5xAzHMVYRgzzbCV" +
"/jkb4Z66En/WpGuisjryFIkGsFqrWN0XAXx+NQuUpyyJ70VPnz5jfapc7RNS7mltXLly" +
"tj5nzipzbPG+gTrrTzIwQ2guTZmhHUoXxdteGnYkd/6hfUR8cMsr6dM6jcwt+nokkbkL" +
"JBdseWXY6+dH5a6iw3dLUiuYsQJEPwXQurU07b7OM3c9ery3DLceAdHHgvl1xVQYIvzG" +
"AUzshXCqTsP65NtsxioQWgAVw2w/kFLQuGfPykw9a84eqzPV3D2vZgQJ7UEp9YfYDtXa" +
"mhwvLHs5QTRvKU2b3AW4+ND1YOwQQi3cXDJ8be78QwsZGCXAUgFDCdRPET8uGGMBiqlM" +
"WDcBHo9yMkVZ2RQ7d75vEzMGMMmFUqqO0b2H/dMBGym/zBB1Fe6PwBAgvAxgBYMWpuQH" +
"3nLq/5KdrA42f+Y69WXIdFKNA2pcsW+iYLzDjBIQZwHUWlmaNqnTsNzimiywtoFhL2PI" +
"YQTOZfDbAH1B4CwCTSfiJxXTHQTun5gQk/emZ2Aw3XPA8HkywuOKfZXElFJZmjYykik9" +
"LLrSWl1F0iyXIVaFgmqa5rI+NsO680LXJufXzedIo3ZhIv/Bi75qAvwMpEChrnJ52r1d" +
"kSg6MlqStYZBxwFKZ4XpW1ek7XTuTiiq6W+SfA/Ez4FxB0EkbylNG3fem4ljoR1hoFLY" +
"eJ50Kdtq/AcjHG7cFN/XDOu7AWpOzg+kH/DCiJdJXzFLocX7s5wK9+CivZnfne3WM0rD" +
"4ZYwhWO7dbjskD6VSPwOij1MmE2E+srS9LFdmWXu4dtJU2VgOgxgqFDqKc0V827YDCaC" +
"uIgYs1hxMQTdAubbFctJ21YM2z95ti85aGA5gFGsuISIHgNwshurWyKAAxXJy7q5sLA1" +
"qGb1za9/zVnzlyeu6h7TbdbZjmNT3flYN3XBvj+22noRA8cY6CBCFJgSFdQaM6ReMlyi" +
"nEDHKkvTZ3R5f77vTmIuZYlXSNEoEPKZcRiMehAsJ4URsEIJSiPmOQT+EKAWJhoEcIKm" +
"xFxbKottVICwrrI0fTY5Pa5N8iunh2i3w2MGT2lqdhTWlSWNj4kxNp0Nth8Qoe/vSCph" +
"c2rWgYk2EE8gYZNqs1l88feSjN0RPj908AZlo3X78uG1nYBnPHYoHh0dQweh+ZCzdgjx" +
"eU5B0Q0+2MduOtAsY+Paw3qo1daeAXFSFJnLJIm+LIi6a+Hq1ctG+bwvfBq97pueg4TR" +
"42jZi/07KFDh9ib20gpPnbH/4J4ceHLPSuhZc2AeW31tVFT34Fp3ojE50Gi9n5zqn0oj" +
"0HSp0nmpNY/HIzwez1VNF+OLD35gM4W3lqbn/W/5TBRYn7iISPaxFXn7Fvi/9Hgg0tNB" +
"zpRR571mIMtgSbcokXe2PcavKLaCYR4DFBT1qvWfnFZ984IFLU4rugRVoroaqKrKsZ0e" +
"0OmxT3qzrlOC7pZojmbWmcggWylACNh2nBYb9VG4LTy9ZuqOJY/31my9dMziF3vGvDug" +
"pSPb0GWzBdkEwWSdbs/aOPxXZZHIXTAidTbzzj9Srwns35QSgzDfJdjKBon+DM1m5gwi" +
"dAjhL0yahG/+VZnqSt1dazoC9yZDZs6G5dwNbEhcBIXHAdpFZCu2NQ0kmahdWZyoubQj" +
"aLMmbc/Z9pdR6a4Qv5bzYK2ufTwmZGUoTXxnsooxGByWetPTSRPC+yN9zeVC4OBd4gF5" +
"zhsanUY/w4PwiQ19R0plvQWmpckFdd7Lyagrd29i4Nvkgrpix/DTHaboHa1HaCKMDFLh" +
"9/lIo0c9/dmUOKkpXj36+TOuPm+KU8ZYSggfYGHYpMKSP+nwhzrnSnLCWZYOutyYEpm/" +
"fOCLp9268uQXQOpGZnKKTBtLinaYAgJJojZWfCsDBSTlFPfEEzVXy/3/5UCHZlecmh0B" +
"jrfLvBAJPlC/G1PlkNza0OkP4noGW4zVhkaTTAsWsTNnkDP02XSu82oTTPOSCgJvOw85" +
"0xE09MezY9mpQp7i87IHwOJ0IiRcSNOIAdkRmZEJ5D9/VBCtnsd7nAAAAABJRU5ErkJg" +
"gg==";
this.logo.render = function (ctx) {
var gradient = ctx.createLinearGradient(
0,
0,
this.width(),
0
);
gradient.addColorStop(0, 'black');
gradient.addColorStop(0.5, myself.frameColor.toString());
ctx.fillStyle = MorphicPreferences.isFlat ?
myself.frameColor.toString() : gradient;
ctx.fillRect(0, 0, this.width(), this.height());
if (this.cachedTexture) {
this.renderCachedTexture(ctx);
} else if (this.texture) {
this.renderTexture(this.texture, ctx);
}
};
this.logo.renderCachedTexture = function (ctx) {
ctx.drawImage(
this.cachedTexture,
5,
Math.round((this.height() - this.cachedTexture.height) / 2)
);
this.changed();
};
this.logo.mouseClickLeft = function () {
myself.snapMenu();
};
this.logo.color = new Color();
this.logo.setExtent(new Point(200, 28)); // dimensions are fixed
this.add(this.logo);
};
IDE_Morph.prototype.createControlBar = function () {
// assumes the logo has already been created
var padding = 5,
button,
slider,
stopButton,
pauseButton,
startButton,
projectButton,
settingsButton,
stageSizeButton,
appModeButton,
steppingButton,
cloudButton,
x,
colors = [
this.groupColor,
this.frameColor.darker(50),
this.frameColor.darker(50)
],
myself = this;
if (this.controlBar) {
this.controlBar.destroy();
}
this.controlBar = new Morph();
this.controlBar.color = this.frameColor;
this.controlBar.setHeight(this.logo.height()); // height is fixed
// let users manually enforce re-layout when changing orientation
// on mobile devices
this.controlBar.mouseClickLeft = function () {
this.world().fillPage();
};
this.add(this.controlBar);
//smallStageButton
button = new ToggleButtonMorph(
null, //colors,
this, // the IDE is the target
'toggleStageSize',
[
new SymbolMorph('smallStage', 14),
new SymbolMorph('normalStage', 14)
],
() => this.isSmallStage // query
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'stage size\nsmall & normal';
button.fixLayout();
button.refresh();
stageSizeButton = button;
this.controlBar.add(stageSizeButton);
this.controlBar.stageSizeButton = button; // for refreshing
//appModeButton
button = new ToggleButtonMorph(
null, //colors,
this, // the IDE is the target
'toggleAppMode',
[
new SymbolMorph('fullScreen', 14),
new SymbolMorph('normalScreen', 14)
],
() => this.isAppMode // query
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'app & edit\nmodes';
button.fixLayout();
button.refresh();
appModeButton = button;
this.controlBar.add(appModeButton);
this.controlBar.appModeButton = appModeButton; // for refreshing
//steppingButton
button = new ToggleButtonMorph(
null, //colors,
this, // the IDE is the target
'toggleSingleStepping',
[
new SymbolMorph('footprints', 16),
new SymbolMorph('footprints', 16)
],
() => Process.prototype.enableSingleStepping // query
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = new Color(153, 255, 213);
// button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
button.hint = 'Visible stepping';
button.fixLayout();
button.refresh();
steppingButton = button;
this.controlBar.add(steppingButton);
this.controlBar.steppingButton = steppingButton; // for refreshing
// stopButton
button = new ToggleButtonMorph(
null, // colors
this, // the IDE is the target
'stopAllScripts',
[
new SymbolMorph('octagon', 14),
new SymbolMorph('square', 14)
],
() => this.stage ? // query
myself.stage.enableCustomHatBlocks &&
myself.stage.threads.pauseCustomHatBlocks
: true
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = new Color(200, 0, 0);
button.contrast = this.buttonContrast;
// button.hint = 'stop\nevery-\nthing';
button.fixLayout();
button.refresh();
stopButton = button;
this.controlBar.add(stopButton);
this.controlBar.stopButton = stopButton; // for refreshing
//pauseButton
button = new ToggleButtonMorph(
null, //colors,
this, // the IDE is the target
'togglePauseResume',
[
new SymbolMorph('pause', 12),
new SymbolMorph('pointRight', 14)
],
() => this.isPaused() // query
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = new Color(255, 220, 0);
button.contrast = this.buttonContrast;
// button.hint = 'pause/resume\nall scripts';
button.fixLayout();
button.refresh();
pauseButton = button;
this.controlBar.add(pauseButton);
this.controlBar.pauseButton = pauseButton; // for refreshing
// startButton
button = new PushButtonMorph(
this,
'pressStart',
new SymbolMorph('flag', 14)
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = new Color(0, 200, 0);
button.contrast = this.buttonContrast;
// button.hint = 'start green\nflag scripts';
button.fixLayout();
startButton = button;
this.controlBar.add(startButton);
this.controlBar.startButton = startButton;
// steppingSlider
slider = new SliderMorph(
61,
1,
Process.prototype.flashTime * 100 + 1,
6,
'horizontal'
);
slider.action = (num) => {
Process.prototype.flashTime = (num - 1) / 100;
this.controlBar.refreshResumeSymbol();
};
// slider.alpha = MorphicPreferences.isFlat ? 0.1 : 0.3;
slider.color = new Color(153, 255, 213);
slider.alpha = 0.3;
slider.setExtent(new Point(50, 14));
this.controlBar.add(slider);
this.controlBar.steppingSlider = slider;
// projectButton
button = new PushButtonMorph(
this,
'projectMenu',
new SymbolMorph('file', 14)
//'\u270E'
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'open, save, & annotate project';
button.fixLayout();
projectButton = button;
this.controlBar.add(projectButton);
this.controlBar.projectButton = projectButton; // for menu positioning
// settingsButton
button = new PushButtonMorph(
this,
'settingsMenu',
new SymbolMorph('gears', 14)
//'\u2699'
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'edit settings';
button.fixLayout();
settingsButton = button;
this.controlBar.add(settingsButton);
this.controlBar.settingsButton = settingsButton; // for menu positioning
// cloudButton
button = new PushButtonMorph(
this,
'cloudMenu',
new SymbolMorph('cloud', 11)
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'cloud operations';
button.fixLayout();
cloudButton = button;
this.controlBar.add(cloudButton);
this.controlBar.cloudButton = cloudButton; // for menu positioning
this.controlBar.fixLayout = function () {
x = this.right() - padding;
[stopButton, pauseButton, startButton].forEach(button => {
button.setCenter(myself.controlBar.center());
button.setRight(x);
x -= button.width();
x -= padding;
}
);
x = Math.min(
startButton.left() - (3 * padding + 2 * stageSizeButton.width()),
myself.right() - StageMorph.prototype.dimensions.x *
(myself.isSmallStage ? myself.stageRatio : 1)
);
[stageSizeButton, appModeButton].forEach(button => {
x += padding;
button.setCenter(myself.controlBar.center());
button.setLeft(x);
x += button.width();
}
);
slider.setCenter(myself.controlBar.center());
slider.setRight(stageSizeButton.left() - padding);
steppingButton.setCenter(myself.controlBar.center());
steppingButton.setRight(slider.left() - padding);
settingsButton.setCenter(myself.controlBar.center());
settingsButton.setLeft(this.left());
cloudButton.setCenter(myself.controlBar.center());
cloudButton.setRight(settingsButton.left() - padding);
projectButton.setCenter(myself.controlBar.center());
projectButton.setRight(cloudButton.left() - padding);
this.refreshSlider();
this.updateLabel();
};
this.controlBar.refreshSlider = function () {
if (Process.prototype.enableSingleStepping && !myself.isAppMode) {
slider.fixLayout();
slider.rerender();
slider.show();
} else {
slider.hide();
}
this.refreshResumeSymbol();
};
this.controlBar.refreshResumeSymbol = function () {
var pauseSymbols;
if (Process.prototype.enableSingleStepping &&
Process.prototype.flashTime > 0.5) {
myself.stage.threads.pauseAll(myself.stage);
pauseSymbols = [
new SymbolMorph('pause', 12),
new SymbolMorph('stepForward', 14)
];
} else {
pauseSymbols = [
new SymbolMorph('pause', 12),
new SymbolMorph('pointRight', 14)
];
}
pauseButton.labelString = pauseSymbols;
pauseButton.createLabel();
pauseButton.fixLayout();
pauseButton.refresh();
};
this.controlBar.updateLabel = function () {
var suffix = myself.world().isDevMode ?
' - ' + localize('development mode') : '';
if (this.label) {
this.label.destroy();
}
if (myself.isAppMode) {
return;
}
this.label = new StringMorph(
(myself.projectName || localize('untitled')) + suffix,
14,
'sans-serif',
true,
false,
false,
MorphicPreferences.isFlat ? null : new Point(2, 1),
myself.frameColor.darker(myself.buttonContrast)
);
this.label.color = myself.buttonLabelColor;
this.label.fixLayout();
this.add(this.label);
this.label.setCenter(this.center());
this.label.setLeft(this.settingsButton.right() + padding);
};
};
IDE_Morph.prototype.createCategories = function () {
var myself = this;
if (this.categories) {
this.categories.destroy();
}
this.categories = new Morph();
this.categories.color = this.groupColor;
this.categories.bounds.setWidth(this.paletteWidth);
function addCategoryButton(category) {
var labelWidth = 75,
colors = [
myself.frameColor,
myself.frameColor.darker(50),
SpriteMorph.prototype.blockColor[category]
],
button;
button = new ToggleButtonMorph(
colors,
myself, // the IDE is the target
() => {
myself.currentCategory = category;
myself.categories.children.forEach(each =>
each.refresh()
);
myself.refreshPalette(true);
},
category[0].toUpperCase().concat(category.slice(1)), // label
() => myself.currentCategory === category, // query
null, // env
null, // hint
labelWidth, // minWidth
true // has preview
);
button.corner = 8;
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = myself.buttonLabelColor;
button.fixLayout();
button.refresh();
myself.categories.add(button);
return button;
}
function fixCategoriesLayout() {
var buttonWidth = myself.categories.children[0].width(),
buttonHeight = myself.categories.children[0].height(),
border = 3,
rows = Math.ceil((myself.categories.children.length) / 2),
xPadding = (200 // myself.logo.width()
- border
- buttonWidth * 2) / 3,
yPadding = 2,
l = myself.categories.left(),
t = myself.categories.top(),
i = 0,
row,
col;
myself.categories.children.forEach(button => {
i += 1;
row = Math.ceil(i / 2);
col = 2 - (i % 2);
button.setPosition(new Point(
l + (col * xPadding + ((col - 1) * buttonWidth)),
t + (row * yPadding + ((row - 1) * buttonHeight) + border)
));
});
myself.categories.setHeight(
(rows + 1) * yPadding
+ rows * buttonHeight
+ 2 * border
);
}
SpriteMorph.prototype.categories.forEach(cat => {
if (!contains(['lists', 'other'], cat)) {
addCategoryButton(cat);
}
});
fixCategoriesLayout();
this.add(this.categories);
};
IDE_Morph.prototype.createPalette = function (forSearching) {
// assumes that the logo pane has already been created
// needs the categories pane for layout
if (this.palette) {
this.palette.destroy();
}
if (forSearching) {
this.palette = new ScrollFrameMorph(
null,
null,
this.currentSprite.sliderColor
);
// search toolbar (floating cancel button):
/* commented out for now
this.palette.toolBar = new PushButtonMorph(
this,
() => {
this.refreshPalette();
this.palette.adjustScrollBars();
},
new SymbolMorph("magnifierOutline", 16)
);
this.palette.toolBar.alpha = 0.2;
this.palette.toolBar.padding = 1;
// this.palette.toolBar.hint = 'Cancel';
this.palette.toolBar.labelShadowColor = new Color(140, 140, 140);
this.palette.toolBar.fixLayout();
this.palette.add(this.palette.toolBar);
*/
} else {
this.palette = this.currentSprite.palette(this.currentCategory);
}
this.palette.isDraggable = false;
this.palette.acceptsDrops = true;
this.palette.enableAutoScrolling = false;
this.palette.contents.acceptsDrops = false;
this.palette.reactToDropOf = (droppedMorph, hand) => {
if (droppedMorph instanceof DialogBoxMorph) {
this.world().add(droppedMorph);
} else if (droppedMorph instanceof SpriteMorph) {
this.removeSprite(droppedMorph);
} else if (droppedMorph instanceof SpriteIconMorph) {
droppedMorph.destroy();
this.removeSprite(droppedMorph.object);
} else if (droppedMorph instanceof CostumeIconMorph) {
this.currentSprite.wearCostume(null);
droppedMorph.perish();
} else if (droppedMorph instanceof BlockMorph) {
this.stage.threads.stopAllForBlock(droppedMorph);
if (hand && hand.grabOrigin.origin instanceof ScriptsMorph) {
hand.grabOrigin.origin.clearDropInfo();
hand.grabOrigin.origin.lastDroppedBlock = droppedMorph;
hand.grabOrigin.origin.recordDrop(hand.grabOrigin);
}
droppedMorph.perish();
} else {
droppedMorph.perish();
}
};
this.palette.contents.reactToDropOf = (droppedMorph) => {
// for "undrop" operation
if (droppedMorph instanceof BlockMorph) {
droppedMorph.destroy();
}
};
this.palette.setWidth(this.logo.width());
this.add(this.palette);
return this.palette;
};
IDE_Morph.prototype.createPaletteHandle = function () {
// assumes that the palette has already been created
if (this.paletteHandle) {this.paletteHandle.destroy(); }
this.paletteHandle = new PaletteHandleMorph(this.categories);
this.add(this.paletteHandle);
};
IDE_Morph.prototype.createStage = function () {
// assumes that the logo pane has already been created
if (this.stage) {this.stage.destroy(); }
StageMorph.prototype.frameRate = 0;
this.stage = new StageMorph(this.globalVariables);
this.stage.setExtent(this.stage.dimensions); // dimensions are fixed
if (this.currentSprite instanceof SpriteMorph) {
this.currentSprite.setPosition(
this.stage.center().subtract(
this.currentSprite.extent().divideBy(2)
)
);
this.stage.add(this.currentSprite);
}
this.add(this.stage);
};
IDE_Morph.prototype.createStageHandle = function () {
// assumes that the stage has already been created
if (this.stageHandle) {this.stageHandle.destroy(); }
this.stageHandle = new StageHandleMorph(this.stage);
this.add(this.stageHandle);
};
IDE_Morph.prototype.createSpriteBar = function () {
// assumes that the categories pane has already been created
var rotationStyleButtons = [],
thumbSize = new Point(45, 45),
nameField,
padlock,
thumbnail,
tabCorner = 15,
tabColors = this.tabColors,
tabBar = new AlignmentMorph('row', -tabCorner * 2),
tab,
symbols = ['\u2192', '\u21BB', '\u2194'],
labels = ['don\'t rotate', 'can rotate', 'only face left/right'],
myself = this;
if (this.spriteBar) {
this.spriteBar.destroy();
}
this.spriteBar = new Morph();
this.spriteBar.color = this.frameColor;
this.add(this.spriteBar);
function addRotationStyleButton(rotationStyle) {
var colors = myself.rotationStyleColors,
button;
button = new ToggleButtonMorph(
colors,
myself, // the IDE is the target
() => {
if (myself.currentSprite instanceof SpriteMorph) {
myself.currentSprite.rotationStyle = rotationStyle;
myself.currentSprite.changed();
myself.currentSprite.fixLayout();
myself.currentSprite.rerender();
}
rotationStyleButtons.forEach(each =>
each.refresh()
);
},
symbols[rotationStyle], // label
() => myself.currentSprite instanceof SpriteMorph // query
&& myself.currentSprite.rotationStyle === rotationStyle,
null, // environment
localize(labels[rotationStyle])
);
button.corner = 8;
button.labelMinExtent = new Point(11, 11);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = myself.buttonLabelColor;
button.fixLayout();
button.refresh();
rotationStyleButtons.push(button);
button.setPosition(myself.spriteBar.position().add(2));
button.setTop(button.top()
+ ((rotationStyleButtons.length - 1) * (button.height() + 2))
);
myself.spriteBar.add(button);
if (myself.currentSprite instanceof StageMorph) {
button.hide();
}
return button;
}
addRotationStyleButton(1);
addRotationStyleButton(2);
addRotationStyleButton(0);
this.rotationStyleButtons = rotationStyleButtons;
thumbnail = new Morph();
thumbnail.isCachingImage = true;
thumbnail.bounds.setExtent(thumbSize);
thumbnail.cachedImage = this.currentSprite.thumbnail(thumbSize);
thumbnail.setPosition(
rotationStyleButtons[0].topRight().add(new Point(5, 3))
);
this.spriteBar.add(thumbnail);
thumbnail.fps = 3;
thumbnail.step = function () {
if (thumbnail.version !== myself.currentSprite.version) {
thumbnail.cachedImage = myself.currentSprite.thumbnail(
thumbSize,
thumbnail.cachedImage
);
thumbnail.changed();
thumbnail.version = myself.currentSprite.version;
}
};
nameField = new InputFieldMorph(this.currentSprite.name);
nameField.setWidth(100); // fixed dimensions
nameField.contrast = 90;
nameField.setPosition(thumbnail.topRight().add(new Point(10, 3)));
this.spriteBar.add(nameField);
this.spriteBar.nameField = nameField;
nameField.fixLayout();
nameField.accept = function () {
var newName = nameField.getValue();
myself.currentSprite.setName(
myself.newSpriteName(newName, myself.currentSprite)
);
nameField.setContents(myself.currentSprite.name);
};
this.spriteBar.reactToEdit = nameField.accept;
// padlock
padlock = new ToggleMorph(
'checkbox',
null,
() => this.currentSprite.isDraggable =
!this.currentSprite.isDraggable,
localize('draggable'),
() => this.currentSprite.isDraggable
);
padlock.label.isBold = false;
padlock.label.setColor(this.buttonLabelColor);
padlock.color = tabColors[2];
padlock.highlightColor = tabColors[0];
padlock.pressColor = tabColors[1];
padlock.tick.shadowOffset = MorphicPreferences.isFlat ?
new Point() : new Point(-1, -1);
padlock.tick.shadowColor = new Color(); // black
padlock.tick.color = this.buttonLabelColor;
padlock.tick.isBold = false;
padlock.tick.fixLayout();
padlock.setPosition(nameField.bottomLeft().add(2));
padlock.fixLayout();
this.spriteBar.add(padlock);
if (this.currentSprite instanceof StageMorph) {
padlock.hide();
}
// tab bar
tabBar.tabTo = function (tabString) {
var active;
myself.currentTab = tabString;
this.children.forEach(each => {
each.refresh();
if (each.state) {active = each; }
});
active.refresh(); // needed when programmatically tabbing
myself.createSpriteEditor();
myself.fixLayout('tabEditor');
};
tab = new TabMorph(
tabColors,
null, // target
() => tabBar.tabTo('scripts'),
localize('Scripts'), // label
() => this.currentTab === 'scripts' // query
);
tab.padding = 3;
tab.corner = tabCorner;
tab.edge = 1;
tab.labelShadowOffset = new Point(-1, -1);
tab.labelShadowColor = tabColors[1];
tab.labelColor = this.buttonLabelColor;
tab.fixLayout();
tabBar.add(tab);
tab = new TabMorph(
tabColors,
null, // target
() => tabBar.tabTo('costumes'),
localize(this.currentSprite instanceof SpriteMorph ?
'Costumes' : 'Backgrounds'
),
() => this.currentTab === 'costumes' // query
);
tab.padding = 3;
tab.corner = tabCorner;
tab.edge = 1;
tab.labelShadowOffset = new Point(-1, -1);
tab.labelShadowColor = tabColors[1];
tab.labelColor = this.buttonLabelColor;
tab.fixLayout();
tabBar.add(tab);
tab = new TabMorph(
tabColors,
null, // target
() => tabBar.tabTo('sounds'),
localize('Sounds'), // label
() => this.currentTab === 'sounds' // query
);
tab.padding = 3;
tab.corner = tabCorner;
tab.edge = 1;
tab.labelShadowOffset = new Point(-1, -1);
tab.labelShadowColor = tabColors[1];
tab.labelColor = this.buttonLabelColor;
tab.fixLayout();
tabBar.add(tab);
tabBar.fixLayout();
tabBar.children.forEach(each =>
each.refresh()
);
this.spriteBar.tabBar = tabBar;
this.spriteBar.add(this.spriteBar.tabBar);
this.spriteBar.fixLayout = function () {
this.tabBar.setLeft(this.left());
this.tabBar.setBottom(this.bottom());
};
};
IDE_Morph.prototype.createSpriteEditor = function () {
// assumes that the logo pane and the stage have already been created
var scripts = this.currentSprite.scripts;
if (this.spriteEditor) {
this.spriteEditor.destroy();
}
if (this.currentTab === 'scripts') {
scripts.isDraggable = false;
scripts.color = this.groupColor;
scripts.cachedTexture = this.scriptsPaneTexture;
this.spriteEditor = new ScrollFrameMorph(
scripts,
null,
this.sliderColor
);
this.spriteEditor.color = this.groupColor;
this.spriteEditor.padding = 10;
this.spriteEditor.growth = 50;
this.spriteEditor.isDraggable = false;
this.spriteEditor.acceptsDrops = false;
this.spriteEditor.contents.acceptsDrops = true;
scripts.scrollFrame = this.spriteEditor;
scripts.updateToolbar();
this.add(this.spriteEditor);
this.spriteEditor.scrollX(this.spriteEditor.padding);
this.spriteEditor.scrollY(this.spriteEditor.padding);
} else if (this.currentTab === 'costumes') {
this.spriteEditor = new WardrobeMorph(
this.currentSprite,
this.sliderColor
);
this.spriteEditor.color = this.groupColor;
this.add(this.spriteEditor);
this.spriteEditor.updateSelection();
this.spriteEditor.acceptsDrops = false;
this.spriteEditor.contents.acceptsDrops = false;
} else if (this.currentTab === 'sounds') {
this.spriteEditor = new JukeboxMorph(
this.currentSprite,
this.sliderColor
);
this.spriteEditor.color = this.groupColor;
this.add(this.spriteEditor);
this.spriteEditor.updateSelection();
this.spriteEditor.acceptDrops = false;
this.spriteEditor.contents.acceptsDrops = false;
} else {
this.spriteEditor = new Morph();
this.spriteEditor.color = this.groupColor;
this.spriteEditor.acceptsDrops = true;
this.spriteEditor.reactToDropOf = (droppedMorph) => {
if (droppedMorph instanceof DialogBoxMorph) {
this.world().add(droppedMorph);
} else if (droppedMorph instanceof SpriteMorph) {
this.removeSprite(droppedMorph);
} else {
droppedMorph.destroy();
}
};
this.add(this.spriteEditor);
}
};
IDE_Morph.prototype.createCorralBar = function () {
// assumes the stage has already been created
var padding = 5,
newbutton,
paintbutton,
cambutton,
colors = [
this.groupColor,
this.frameColor.darker(50),
this.frameColor.darker(50)
];
if (this.corralBar) {
this.corralBar.destroy();
}
this.corralBar = new Morph();
this.corralBar.color = this.frameColor;
this.corralBar.setHeight(this.logo.height()); // height is fixed
this.add(this.corralBar);
// new sprite button
newbutton = new PushButtonMorph(
this,
"addNewSprite",
new SymbolMorph("turtle", 14)
);
newbutton.corner = 12;
newbutton.color = colors[0];
newbutton.highlightColor = colors[1];
newbutton.pressColor = colors[2];
newbutton.labelMinExtent = new Point(36, 18);
newbutton.padding = 0;
newbutton.labelShadowOffset = new Point(-1, -1);
newbutton.labelShadowColor = colors[1];
newbutton.labelColor = this.buttonLabelColor;
newbutton.contrast = this.buttonContrast;
newbutton.hint = "add a new Turtle sprite";
newbutton.fixLayout();
newbutton.setCenter(this.corralBar.center());
newbutton.setLeft(this.corralBar.left() + padding);
this.corralBar.add(newbutton);
paintbutton = new PushButtonMorph(
this,
"paintNewSprite",
new SymbolMorph("brush", 15)
);
paintbutton.corner = 12;
paintbutton.color = colors[0];
paintbutton.highlightColor = colors[1];
paintbutton.pressColor = colors[2];
paintbutton.labelMinExtent = new Point(36, 18);
paintbutton.padding = 0;
paintbutton.labelShadowOffset = new Point(-1, -1);
paintbutton.labelShadowColor = colors[1];
paintbutton.labelColor = this.buttonLabelColor;
paintbutton.contrast = this.buttonContrast;
paintbutton.hint = "paint a new sprite";
paintbutton.fixLayout();
paintbutton.setCenter(this.corralBar.center());
paintbutton.setLeft(
this.corralBar.left() + padding + newbutton.width() + padding
);
this.corralBar.add(paintbutton);
if (CamSnapshotDialogMorph.prototype.enableCamera) {
cambutton = new PushButtonMorph(
this,
"newCamSprite",
new SymbolMorph("camera", 15)
);
cambutton.corner = 12;
cambutton.color = colors[0];
cambutton.highlightColor = colors[1];
cambutton.pressColor = colors[2];
cambutton.labelMinExtent = new Point(36, 18);
cambutton.padding = 0;
cambutton.labelShadowOffset = new Point(-1, -1);
cambutton.labelShadowColor = colors[1];
cambutton.labelColor = this.buttonLabelColor;
cambutton.contrast = this.buttonContrast;
cambutton.hint = "take a camera snapshot and\n" +
"import it as a new sprite";
cambutton.fixLayout();
cambutton.setCenter(this.corralBar.center());
cambutton.setLeft(
this.corralBar.left() +
padding +
newbutton.width() +
padding +
paintbutton.width() +
padding
);
this.corralBar.add(cambutton);
document.addEventListener(
'cameraDisabled',
event => {
cambutton.disable();
cambutton.hint =
CamSnapshotDialogMorph.prototype.notSupportedMessage;
}
);
}
};
IDE_Morph.prototype.createCorral = function () {
// assumes the corral bar has already been created
var frame, padding = 5, myself = this;
this.createStageHandle();
this.createPaletteHandle();
if (this.corral) {
this.corral.destroy();
}
this.corral = new Morph();
this.corral.color = this.groupColor;
this.add(this.corral);
this.corral.stageIcon = new SpriteIconMorph(this.stage);
this.corral.stageIcon.isDraggable = false;
this.corral.add(this.corral.stageIcon);
frame = new ScrollFrameMorph(null, null, this.sliderColor);
frame.acceptsDrops = false;
frame.contents.acceptsDrops = false;
frame.contents.wantsDropOf = (morph) => morph instanceof SpriteIconMorph;
frame.contents.reactToDropOf = (spriteIcon) =>
this.corral.reactToDropOf(spriteIcon);
frame.alpha = 0;
this.sprites.asArray().forEach(morph => {
if (!morph.isTemporary) {
frame.contents.add(new SpriteIconMorph(morph));
}
});
this.corral.frame = frame;
this.corral.add(frame);
this.corral.fixLayout = function () {
this.stageIcon.setCenter(this.center());
this.stageIcon.setLeft(this.left() + padding);
this.frame.setLeft(this.stageIcon.right() + padding);
this.frame.setExtent(new Point(
this.right() - this.frame.left(),
this.height()
));
this.arrangeIcons();
this.refresh();
};
this.corral.arrangeIcons = function () {
var x = this.frame.left(),
y = this.frame.top(),
max = this.frame.right(),
start = this.frame.left();
this.frame.contents.children.forEach(icon => {
var w = icon.width();
if (x + w > max) {
x = start;
y += icon.height(); // they're all the same
}
icon.setPosition(new Point(x, y));
x += w;
});
this.frame.contents.adjustBounds();
};
this.corral.addSprite = function (sprite) {
this.frame.contents.add(new SpriteIconMorph(sprite));
this.fixLayout();
};
this.corral.refresh = function () {
this.stageIcon.refresh();
this.frame.contents.children.forEach(icon =>
icon.refresh()
);
};
this.corral.wantsDropOf = (morph) => morph instanceof SpriteIconMorph;
this.corral.reactToDropOf = function (spriteIcon) {
var idx = 1,
pos = spriteIcon.position();
spriteIcon.destroy();
this.frame.contents.children.forEach(icon => {
if (pos.gt(icon.position()) || pos.y > icon.bottom()) {
idx += 1;
}
});
myself.sprites.add(spriteIcon.object, idx);
myself.createCorral();
myself.fixLayout();
};
};
// IDE_Morph layout
IDE_Morph.prototype.fixLayout = function (situation) {
// situation is a string, i.e.
// 'selectSprite' or 'refreshPalette' or 'tabEditor'
var padding = this.padding,
flag,
maxPaletteWidth;
if (situation !== 'refreshPalette') {
// controlBar
this.controlBar.setPosition(this.logo.topRight());
this.controlBar.setWidth(this.right() - this.controlBar.left());
this.controlBar.fixLayout();
// categories
this.categories.setLeft(this.logo.left());
this.categories.setTop(this.logo.bottom());
this.categories.setWidth(this.paletteWidth);
}
// palette
this.palette.setLeft(this.logo.left());
this.palette.setTop(this.categories.bottom());
this.palette.setHeight(this.bottom() - this.palette.top());
this.palette.setWidth(this.paletteWidth);
if (situation !== 'refreshPalette') {
// stage
if (this.isEmbedMode) {
this.stage.setScale(Math.floor(Math.min(
this.width() / this.stage.dimensions.x,
this.height() / this.stage.dimensions.y
) * 100) / 100);
flag = this.embedPlayButton.flag;
flag.size = Math.floor(Math.min(
this.width(), this.height())) / 5;
flag.setWidth(flag.size);
flag.setHeight(flag.size);
this.embedPlayButton.size = flag.size * 1.6;
this.embedPlayButton.setWidth(this.embedPlayButton.size);
this.embedPlayButton.setHeight(this.embedPlayButton.size);
if (this.embedOverlay) {
this.embedOverlay.setExtent(this.extent());
}
this.stage.setCenter(this.center());
this.embedPlayButton.setCenter(this.stage.center());
flag.setCenter(this.embedPlayButton.center());
flag.setLeft(flag.left() + flag.size * 0.1); // account for slight asymmetry
} else if (this.isAppMode) {
this.stage.setScale(Math.floor(Math.min(
(this.width() - padding * 2) / this.stage.dimensions.x,
(this.height() - this.controlBar.height() * 2 - padding * 2)
/ this.stage.dimensions.y
) * 10) / 10);
this.stage.setCenter(this.center());
} else {
this.stage.setScale(this.isSmallStage ? this.stageRatio : 1);
this.stage.setTop(this.logo.bottom() + padding);
this.stage.setRight(this.right());
maxPaletteWidth = Math.max(
200,
this.width() -
this.stage.width() -
this.spriteBar.tabBar.width() -
(this.padding * 2)
);
if (this.paletteWidth > maxPaletteWidth) {
this.paletteWidth = maxPaletteWidth;
this.fixLayout();
}
this.stageHandle.fixLayout();
this.paletteHandle.fixLayout();
}
// spriteBar
this.spriteBar.setLeft(this.paletteWidth + padding);
this.spriteBar.setTop(this.logo.bottom() + padding);
this.spriteBar.setExtent(new Point(
Math.max(0, this.stage.left() - padding - this.spriteBar.left()),
this.categories.bottom() - this.spriteBar.top() - padding
));
this.spriteBar.fixLayout();
// spriteEditor
if (this.spriteEditor.isVisible) {
this.spriteEditor.setPosition(this.spriteBar.bottomLeft());
this.spriteEditor.setExtent(new Point(
this.spriteBar.width(),
this.bottom() - this.spriteEditor.top()
));
}
// corralBar
this.corralBar.setLeft(this.stage.left());
this.corralBar.setTop(this.stage.bottom() + padding);
this.corralBar.setWidth(this.stage.width());
// corral
if (!contains(['selectSprite', 'tabEditor'], situation)) {
this.corral.setPosition(this.corralBar.bottomLeft());
this.corral.setWidth(this.stage.width());
this.corral.setHeight(this.bottom() - this.corral.top());
this.corral.fixLayout();
}
}
};
IDE_Morph.prototype.setProjectName = function (string) {
this.projectName = string.replace(/['"]/g, ''); // filter quotation marks
this.hasChangedMedia = true;
this.controlBar.updateLabel();
};
// IDE_Morph resizing
IDE_Morph.prototype.setExtent = function (point) {
var padding = new Point(430, 110),
minExt,
ext,
maxWidth,
minWidth,
maxHeight,
minRatio,
maxRatio;
// determine the minimum dimensions making sense for the current mode
if (this.isAppMode) {
if (this.isEmbedMode) {
minExt = new Point(100, 100);
} else {
minExt = StageMorph.prototype.dimensions.add(
this.controlBar.height() + 10
);
}
} else {
if (this.stageRatio > 1) {
minExt = padding.add(StageMorph.prototype.dimensions);
} else {
minExt = padding.add(
StageMorph.prototype.dimensions.multiplyBy(this.stageRatio)
);
}
}
ext = point.max(minExt);
// adjust stage ratio if necessary
maxWidth = ext.x -
(200 + this.spriteBar.tabBar.width() + (this.padding * 2));
minWidth = SpriteIconMorph.prototype.thumbSize.x * 3;
maxHeight = (ext.y - SpriteIconMorph.prototype.thumbSize.y * 3.5);
minRatio = minWidth / this.stage.dimensions.x;
maxRatio = Math.min(
(maxWidth / this.stage.dimensions.x),
(maxHeight / this.stage.dimensions.y)
);
this.stageRatio = Math.min(maxRatio, Math.max(minRatio, this.stageRatio));
// apply
IDE_Morph.uber.setExtent.call(this, ext);
this.fixLayout();
};
// IDE_Morph events
IDE_Morph.prototype.reactToWorldResize = function (rect) {
if (this.isAutoFill) {
this.setPosition(rect.origin);
this.setExtent(rect.extent());
}
if (this.filePicker) {
document.body.removeChild(this.filePicker);
this.filePicker = null;
}
};
IDE_Morph.prototype.droppedImage = function (aCanvas, name) {
var costume = new Costume(
aCanvas,
this.currentSprite.newCostumeName(
name ? name.split('.')[0] : '' // up to period
)
);
if (costume.isTainted()) {
this.inform(
'Unable to import this image',
'The picture you wish to import has been\n' +
'tainted by a restrictive cross-origin policy\n' +
'making it unusable for costumes in Snap!. \n\n' +
'Try downloading this picture first to your\n' +
'computer, and import it from there.'
);
return;
}
this.currentSprite.addCostume(costume);
this.currentSprite.wearCostume(costume);
this.spriteBar.tabBar.tabTo('costumes');
this.hasChangedMedia = true;
};
IDE_Morph.prototype.droppedSVG = function (anImage, name) {
var costume = new SVG_Costume(anImage, name.split('.')[0]);
this.currentSprite.addCostume(costume);
this.currentSprite.wearCostume(costume);
this.spriteBar.tabBar.tabTo('costumes');
this.hasChangedMedia = true;
};
IDE_Morph.prototype.droppedAudio = function (anAudio, name) {
if (anAudio.src.indexOf('data:audio') !== 0) {
// fetch and base 64 encode samples using FileReader
this.getURL(
anAudio.src,
blob => {
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
var base64 = reader.result;
base64 = 'data:audio/ogg;base64,' +
base64.split(',')[1];
anAudio.src = base64;
this.droppedAudio(anAudio, name);
};
},
'blob'
);
} else {
this.currentSprite.addSound(anAudio, name.split('.')[0]); // up to '.'
this.spriteBar.tabBar.tabTo('sounds');
this.hasChangedMedia = true;
}
};
IDE_Morph.prototype.droppedText = function (aString, name, fileType) {
var lbl = name ? name.split('.')[0] : '',
ext = name ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : '';
// check for Snap specific files, projects, libraries, sprites, scripts
if (aString.indexOf('<project') === 0) {
location.hash = '';
return this.openProjectString(aString);
}
if (aString.indexOf('<snapdata') === 0) {
location.hash = '';
return this.openCloudDataString(aString);
}
if (aString.indexOf('<blocks') === 0) {
return this.openBlocksString(aString, lbl, true);
}
if (aString.indexOf('<sprites') === 0) {
return this.openSpritesString(aString);
}
if (aString.indexOf('<media') === 0) {
return this.openMediaString(aString);
}
if (aString.indexOf('<script') === 0) {
return this.openScriptString(aString);
}
// check for encoded data-sets, CSV, JSON
if (fileType.indexOf('csv') !== -1 || ext === 'csv') {
return this.openDataString(aString, lbl, 'csv');
}
if (fileType.indexOf('json') !== -1 || ext === 'json') {
return this.openDataString(aString, lbl, 'json');
}
// import as plain text data
this.openDataString(aString, lbl, 'text');
};
IDE_Morph.prototype.droppedBinary = function (anArrayBuffer, name) {
// dynamically load ypr->Snap!
var ypr = document.getElementById('ypr'),
myself = this,
suffix = name.substring(name.length - 3);
if (suffix.toLowerCase() !== 'ypr') {return; }
function loadYPR(buffer, lbl) {
var reader = new sb.Reader(),
pname = lbl.split('.')[0]; // up to period
reader.onload = function (info) {
myself.droppedText(new sb.XMLWriter().write(pname, info));
};
reader.readYPR(new Uint8Array(buffer));
}
if (!ypr) {
ypr = document.createElement('script');
ypr.id = 'ypr';
ypr.onload = function () {loadYPR(anArrayBuffer, name); };
document.head.appendChild(ypr);
ypr.src = this.resourceURL('src', 'ypr.js');
} else {
loadYPR(anArrayBuffer, name);
}
};
// IDE_Morph button actions
IDE_Morph.prototype.refreshPalette = function (shouldIgnorePosition) {
var oldTop = this.palette.contents.top();
this.createPalette();
if (this.isAppMode) {
this.palette.hide();
return;
}
this.fixLayout('refreshPalette');
if (!shouldIgnorePosition) {
this.palette.contents.setTop(oldTop);
}
};
IDE_Morph.prototype.pressStart = function () {
if (this.world().currentKey === 16) { // shiftClicked
this.toggleFastTracking();
} else {
this.stage.threads.pauseCustomHatBlocks = false;
this.controlBar.stopButton.refresh();
this.runScripts();
}
};
IDE_Morph.prototype.toggleFastTracking = function () {
if (this.stage.isFastTracked) {
this.stopFastTracking();
} else {
this.startFastTracking();
}
};
IDE_Morph.prototype.toggleVariableFrameRate = function () {
if (StageMorph.prototype.frameRate) {
StageMorph.prototype.frameRate = 0;
this.stage.fps = 0;
} else {
StageMorph.prototype.frameRate = 30;
this.stage.fps = 30;
}
};
IDE_Morph.prototype.toggleSingleStepping = function () {
this.stage.threads.toggleSingleStepping();
this.controlBar.steppingButton.refresh();
this.controlBar.refreshSlider();
};
IDE_Morph.prototype.toggleCameraSupport = function () {
CamSnapshotDialogMorph.prototype.enableCamera =
!CamSnapshotDialogMorph.prototype.enableCamera;
this.spriteBar.tabBar.tabTo(this.currentTab);
this.createCorralBar();
this.fixLayout();
};
IDE_Morph.prototype.startFastTracking = function () {
this.stage.isFastTracked = true;
this.stage.fps = 0;
this.controlBar.startButton.labelString = new SymbolMorph('flash', 14);
this.controlBar.startButton.createLabel();
this.controlBar.startButton.fixLayout();
this.controlBar.startButton.rerender();
};
IDE_Morph.prototype.stopFastTracking = function () {
this.stage.isFastTracked = false;
this.stage.fps = this.stage.frameRate;
this.controlBar.startButton.labelString = new SymbolMorph('flag', 14);
this.controlBar.startButton.createLabel();
this.controlBar.startButton.fixLayout();
this.controlBar.startButton.rerender();
};
IDE_Morph.prototype.runScripts = function () {
this.stage.fireGreenFlagEvent();
};
IDE_Morph.prototype.togglePauseResume = function () {
if (this.stage.threads.isPaused()) {
this.stage.threads.resumeAll(this.stage);
} else {
this.stage.threads.pauseAll(this.stage);
}
this.controlBar.pauseButton.refresh();
};
IDE_Morph.prototype.isPaused = function () {
if (!this.stage) {return false; }
return this.stage.threads.isPaused();
};
IDE_Morph.prototype.stopAllScripts = function () {
if (this.stage.enableCustomHatBlocks) {
this.stage.threads.pauseCustomHatBlocks =
!this.stage.threads.pauseCustomHatBlocks;
} else {
this.stage.threads.pauseCustomHatBlocks = false;
}
this.controlBar.stopButton.refresh();
this.stage.fireStopAllEvent();
};
IDE_Morph.prototype.selectSprite = function (sprite) {
// prevent switching to another sprite if a block editor is open
// so local blocks of different sprites don't mix
if (
detect(
this.world().children,
morph => morph instanceof BlockEditorMorph ||
morph instanceof BlockDialogMorph
)
) {
return;
}
if (this.currentSprite && this.currentSprite.scripts.focus) {
this.currentSprite.scripts.focus.stopEditing();
}
this.currentSprite = sprite;
this.createPalette();
this.createSpriteBar();
this.createSpriteEditor();
this.corral.refresh();
this.fixLayout('selectSprite');
this.currentSprite.scripts.fixMultiArgs();
};
// IDE_Morph retina display support
IDE_Morph.prototype.toggleRetina = function () {
if (isRetinaEnabled()) {
disableRetinaSupport();
} else {
enableRetinaSupport();
}
this.world().fillPage();
IDE_Morph.prototype.scriptsPaneTexture = this.scriptsTexture();
this.stage.clearPenTrails();
this.refreshIDE();
};
// IDE_Morph skins
IDE_Morph.prototype.defaultDesign = function () {
this.setDefaultDesign();
this.refreshIDE();
this.removeSetting('design');
};
IDE_Morph.prototype.flatDesign = function () {
this.setFlatDesign();
this.refreshIDE();
this.saveSetting('design', 'flat');
};
IDE_Morph.prototype.refreshIDE = function () {
var projectData;
if (Process.prototype.isCatchingErrors) {
try {
projectData = this.serializer.serialize(this.stage);
} catch (err) {
this.showMessage('Serialization failed: ' + err);
}
} else {
projectData = this.serializer.serialize(this.stage);
}
SpriteMorph.prototype.initBlocks();
this.buildPanes();
this.fixLayout();
if (this.loadNewProject) {
this.newProject();
} else {
this.openProjectString(projectData);
}
};
// IDE_Morph settings persistance
IDE_Morph.prototype.applySavedSettings = function () {
var design = this.getSetting('design'),
zoom = this.getSetting('zoom'),
language = this.getSetting('language'),
click = this.getSetting('click'),
longform = this.getSetting('longform'),
longurls = this.getSetting('longurls'),
plainprototype = this.getSetting('plainprototype'),
keyboard = this.getSetting('keyboard'),
tables = this.getSetting('tables'),
tableLines = this.getSetting('tableLines'),
autoWrapping = this.getSetting('autowrapping');
// design
if (design === 'flat') {
this.setFlatDesign();
} else {
this.setDefaultDesign();
}
// blocks zoom
if (zoom) {
SyntaxElementMorph.prototype.setScale(Math.min(zoom, 12));
CommentMorph.prototype.refreshScale();
SpriteMorph.prototype.initBlocks();
}
// language
if (language && language !== 'en') {
this.userLanguage = language;
} else {
this.userLanguage = null;
}
// click
if (click && !BlockMorph.prototype.snapSound) {
BlockMorph.prototype.toggleSnapSound();
}
// long form
if (longform) {
InputSlotDialogMorph.prototype.isLaunchingExpanded = true;
}
// project data in URLs
if (longurls) {
this.projectsInURLs = true;
} else {
this.projectsInURLs = false;
}
// keyboard editing
if (keyboard === 'false') {
ScriptsMorph.prototype.enableKeyboard = false;
} else {
ScriptsMorph.prototype.enableKeyboard = true;
}
// tables
if (tables === 'false') {
List.prototype.enableTables = false;
} else {
List.prototype.enableTables = true;
}
// tableLines
if (tableLines) {
TableMorph.prototype.highContrast = true;
} else {
TableMorph.prototype.highContrast = false;
}
// nested auto-wrapping
if (autoWrapping === 'false') {
ScriptsMorph.prototype.enableNestedAutoWrapping = false;
} else {
ScriptsMorph.prototype.enableNestedAutoWrapping = true;
}
// plain prototype labels
if (plainprototype) {
BlockLabelPlaceHolderMorph.prototype.plainLabel = true;
}
};
IDE_Morph.prototype.saveSetting = function (key, value) {
if (!this.savingPreferences) {
return;
}
if (this.hasLocalStorage()) {
localStorage['-snap-setting-' + key] = value;
}
};
IDE_Morph.prototype.getSetting = function (key) {
if (this.hasLocalStorage()) {
return localStorage['-snap-setting-' + key];
}
return null;
};
IDE_Morph.prototype.removeSetting = function (key) {
if (this.hasLocalStorage()) {
delete localStorage['-snap-setting-' + key];
}
};
IDE_Morph.prototype.hasLocalStorage = function () {
// checks whether localStorage is available,
// this kludgy try/catch mechanism is needed
// because Safari 11 is paranoid about accessing
// localstorage from the file:// protocol
try {
return !isNil(localStorage);
} catch (err) {
return false;
}
};
// IDE_Morph sprite list access
IDE_Morph.prototype.addNewSprite = function () {
var sprite = new SpriteMorph(this.globalVariables),
rnd = Process.prototype.reportBasicRandom;
sprite.name = this.newSpriteName(sprite.name);
sprite.setCenter(this.stage.center());
this.stage.add(sprite);
sprite.fixLayout();
sprite.rerender();
// randomize sprite properties
sprite.setColorComponentHSVA(0, rnd.call(this, 0, 100));
sprite.setColorComponentHSVA(1, 100);
sprite.setColorComponentHSVA(2, rnd.call(this, 50, 100));
sprite.setXPosition(rnd.call(this, -220, 220));
sprite.setYPosition(rnd.call(this, -160, 160));
if (this.world().currentKey === 16) { // shift-click
sprite.turn(rnd.call(this, 1, 360));
}
this.sprites.add(sprite);
this.corral.addSprite(sprite);
this.selectSprite(sprite);
};
IDE_Morph.prototype.paintNewSprite = function () {
var sprite = new SpriteMorph(this.globalVariables),
cos = new Costume();
sprite.name = this.newSpriteName(sprite.name);
sprite.setCenter(this.stage.center());
this.stage.add(sprite);
this.sprites.add(sprite);
this.corral.addSprite(sprite);
this.selectSprite(sprite);
cos.edit(
this.world(),
this,
true,
() => this.removeSprite(sprite),
() => {
sprite.addCostume(cos);
sprite.wearCostume(cos);
}
);
};
IDE_Morph.prototype.newCamSprite = function () {
var sprite = new SpriteMorph(this.globalVariables),
camDialog;
sprite.name = this.newSpriteName(sprite.name);
sprite.setCenter(this.stage.center());
this.stage.add(sprite);
this.sprites.add(sprite);
this.corral.addSprite(sprite);
this.selectSprite(sprite);
camDialog = new CamSnapshotDialogMorph(
this,
sprite,
() => this.removeSprite(sprite),
function (costume) { // needs to be "function" to it can access "this"
sprite.addCostume(costume);
sprite.wearCostume(costume);
this.close();
});
camDialog.popUp(this.world());
};
IDE_Morph.prototype.recordNewSound = function () {
var soundRecorder;
soundRecorder = new SoundRecorderDialogMorph(
audio => {
var sound;
if (audio) {
sound = this.currentSprite.addSound(
audio,
this.newSoundName('recording')
);
this.makeSureRecordingIsMono(sound);
this.spriteBar.tabBar.tabTo('sounds');
this.hasChangedMedia = true;
}
});
soundRecorder.key = 'microphone';
soundRecorder.popUp(this.world());
};
IDE_Morph.prototype.makeSureRecordingIsMono = function (sound) {
// private and temporary, a horrible kludge to work around browsers'
// reluctance to implement audio recording constraints that let us
// record sound in mono only. As of January 2020 the audio channelCount
// constraint only works in Firefox, hence this terrible function to
// force convert a stereo sound to mono for Chrome.
// If this code is still here next year, something is very wrong.
// -Jens
decodeSound(sound, makeMono);
function decodeSound(sound, callback) {
var base64, binaryString, len, bytes, i, arrayBuffer, audioCtx;
if (sound.audioBuffer) {
return callback (sound);
}
base64 = sound.audio.src.split(',')[1];
binaryString = window.atob(base64);
len = binaryString.length;
bytes = new Uint8Array(len);
for (i = 0; i < len; i += 1) {
bytes[i] = binaryString.charCodeAt(i);
}
arrayBuffer = bytes.buffer;
audioCtx = Note.prototype.getAudioContext();
sound.isDecoding = true;
audioCtx.decodeAudioData(
arrayBuffer,
buffer => {
sound.audioBuffer = buffer;
return callback (sound);
},
err => {throw err; }
);
}
function makeMono(sound) {
var samples, audio, blob, reader;
if (sound.audioBuffer.numberOfChannels === 1) {return; }
samples = sound.audioBuffer.getChannelData(0);
audio = new Audio();
blob = new Blob(
[
audioBufferToWav(
encodeSound(samples, 44100).audioBuffer
)
],
{type: "audio/wav"}
);
reader = new FileReader();
reader.onload = () => {
audio.src = reader.result;
sound.audio = audio; // .... aaaand we're done!
sound.audioBuffer = null;
sound.cachedSamples = null;
sound.isDecoding = false;
// console.log('made mono', sound);
};
reader.readAsDataURL(blob);
}
function encodeSound(samples, rate) {
var ctx = Note.prototype.getAudioContext(),
frameCount = samples.length,
arrayBuffer = ctx.createBuffer(1, frameCount, +rate || 44100),
i,
source;
if (!arrayBuffer.copyToChannel) {
arrayBuffer.copyToChannel = function (src, channel) {
var buffer = this.getChannelData(channel);
for (i = 0; i < src.length; i += 1) {
buffer[i] = src[i];
}
};
}
arrayBuffer.copyToChannel(
Float32Array.from(samples),
0,
0
);
source = ctx.createBufferSource();
source.buffer = arrayBuffer;
source.audioBuffer = source.buffer;
return source;
}
function audioBufferToWav(buffer, opt) {
var sampleRate = buffer.sampleRate,
format = (opt || {}).float32 ? 3 : 1,
bitDepth = format === 3 ? 32 : 16,
result;
result = buffer.getChannelData(0);
return encodeWAV(result, format, sampleRate, 1, bitDepth);
}
function encodeWAV(
samples,
format,
sampleRate,
numChannels,
bitDepth
) {
var bytesPerSample = bitDepth / 8,
blockAlign = numChannels * bytesPerSample,
buffer = new ArrayBuffer(44 + samples.length * bytesPerSample),
view = new DataView(buffer);
function writeFloat32(output, offset, input) {
for (var i = 0; i < input.length; i += 1, offset += 4) {
output.setFloat32(offset, input[i], true);
}
}
function floatTo16BitPCM(output, offset, input) {
var i, s;
for (i = 0; i < input.length; i += 1, offset += 2) {
s = Math.max(-1, Math.min(1, input[i]));
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
}
}
function writeString(view, offset, string) {
for (var i = 0; i < string.length; i += 1) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
writeString(view, 0, 'RIFF'); // RIFF identifier
// RIFF chunk length:
view.setUint32(4, 36 + samples.length * bytesPerSample, true);
writeString(view, 8, 'WAVE'); // RIFF type
writeString(view, 12, 'fmt '); // format chunk identifier
view.setUint32(16, 16, true); // format chunk length
view.setUint16(20, format, true); // sample format (raw)
view.setUint16(22, numChannels, true); // channel count
view.setUint32(24, sampleRate, true); // sample rate
// byte rate (sample rate * block align):
view.setUint32(28, sampleRate * blockAlign, true);
// block align (channel count * bytes per sample):
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitDepth, true); // bits per sample
writeString(view, 36, 'data'); // data chunk identifier
// data chunk length:
view.setUint32(40, samples.length * bytesPerSample, true);
if (format === 1) { // Raw PCM
floatTo16BitPCM(view, 44, samples);
} else {
writeFloat32(view, 44, samples);
}
return buffer;
}
};
IDE_Morph.prototype.duplicateSprite = function (sprite) {
var duplicate = sprite.fullCopy();
duplicate.isDown = false;
duplicate.setPosition(this.world().hand.position());
duplicate.appearIn(this);
duplicate.keepWithin(this.stage);
duplicate.isDown = sprite.isDown;
this.selectSprite(duplicate);
};
IDE_Morph.prototype.instantiateSprite = function (sprite) {
var instance = sprite.fullCopy(true),
hats = instance.allHatBlocksFor('__clone__init__');
instance.isDown = false;
instance.appearIn(this);
if (hats.length) {
instance.initClone(hats);
} else {
instance.setPosition(this.world().hand.position());
instance.keepWithin(this.stage);
}
instance.isDown = sprite.isDown;
this.selectSprite(instance);
};
IDE_Morph.prototype.removeSprite = function (sprite) {
var idx;
sprite.parts.slice().forEach(part =>
this.removeSprite(part)
);
idx = this.sprites.asArray().indexOf(sprite) + 1;
this.stage.threads.stopAllForReceiver(sprite);
sprite.corpsify();
sprite.destroy();
this.stage.watchers().forEach(watcher => {
if (watcher.object() === sprite) {
watcher.destroy();
}
});
if (idx > 0) {
this.sprites.remove(idx);
}
this.createCorral();
this.fixLayout();
this.currentSprite = detect(
this.stage.children,
morph => morph instanceof SpriteMorph && !morph.isTemporary
) || this.stage;
this.selectSprite(this.currentSprite);
};
IDE_Morph.prototype.newSoundName = function (name) {
var lastSound = this.currentSprite.sounds.at(
this.currentSprite.sounds.length()
);
return this.newName(
name || lastSound.name,
this.currentSprite.sounds.asArray().map(eachSound =>
eachSound.name
)
);
};
IDE_Morph.prototype.newSpriteName = function (name, ignoredSprite) {
var all = this.sprites.asArray().concat(this.stage).filter(each =>
each !== ignoredSprite
).map(each => each.name);
return this.newName(name, all);
};
IDE_Morph.prototype.newName = function (name, elements) {
var ix = name.indexOf('('),
stem = (ix < 0) ? name : name.substring(0, ix),
count = 1,
newName = stem;
while (contains(elements, newName)) {
count += 1;
newName = stem + '(' + count + ')';
}
return newName;
};
// IDE_Morph deleting scripts
IDE_Morph.prototype.removeBlock = function (aBlock, justThis) {
this.stage.threads.stopAllForBlock(aBlock);
aBlock.destroy(justThis);
};
// IDE_Morph menus
IDE_Morph.prototype.userMenu = function () {
var menu = new MenuMorph(this);
// menu.addItem('help', 'nop');
return menu;
};
IDE_Morph.prototype.snapMenu = function () {
var menu,
world = this.world();
menu = new MenuMorph(this);
menu.addItem('About...', 'aboutSnap');
menu.addLine();
menu.addItem(
'Reference manual',
() => {
var url = this.resourceURL('help', 'SnapManual.pdf');
window.open(url, 'SnapReferenceManual');
}
);
menu.addItem(
'Snap! website',
() => window.open('https://snap.berkeley.edu/', 'SnapWebsite')
);
menu.addItem(
'Download source',
() => window.open(
'https://github.com/jmoenig/Snap/releases/latest',
'SnapSource'
)
);
if (world.isDevMode) {
menu.addLine();
menu.addItem(
'Switch back to user mode',
'switchToUserMode',
'disable deep-Morphic\ncontext menus'
+ '\nand show user-friendly ones',
new Color(0, 100, 0)
);
} else if (world.currentKey === 16) { // shift-click
menu.addLine();
menu.addItem(
'Switch to dev mode',
'switchToDevMode',
'enable Morphic\ncontext menus\nand inspectors,'
+ '\nnot user-friendly!',
new Color(100, 0, 0)
);
}
menu.popup(world, this.logo.bottomLeft());
};
IDE_Morph.prototype.cloudMenu = function () {
var menu,
world = this.world(),
pos = this.controlBar.cloudButton.bottomLeft(),
shiftClicked = (world.currentKey === 16);
if (location.protocol === 'file:' && !shiftClicked) {
this.showMessage('cloud unavailable without a web server.');
return;
}
menu = new MenuMorph(this);
if (shiftClicked) {
menu.addItem(
'url...',
'setCloudURL',
null,
new Color(100, 0, 0)
);
menu.addLine();
}
if (!this.cloud.username) {
menu.addItem(
'Login...',
'initializeCloud'
);
menu.addItem(
'Signup...',
'createCloudAccount'
);
menu.addItem(
'Reset Password...',
'resetCloudPassword'
);
menu.addItem(
'Resend Verification Email...',
'resendVerification'
);
} else {
menu.addItem(
localize('Logout') + ' ' + this.cloud.username,
'logout'
);
menu.addItem(
'Change Password...',
'changeCloudPassword'
);
}
if (this.hasCloudProject()) {
menu.addLine();
menu.addItem(
'Open in Community Site',
() => {
var dict = this.urlParameters();
window.open(
this.cloud.showProjectPath(
dict.Username, dict.ProjectName
),
'_blank'
);
}
);
}
if (shiftClicked) {
menu.addLine();
menu.addItem(
'export project media only...',
() => {
if (this.projectName) {
this.exportProjectMedia(this.projectName);
} else {
this.prompt(
'Export Project As...',
name => this.exportProjectMedia(name),
null,
'exportProject'
);
}
},
null,
this.hasChangedMedia ? new Color(100, 0, 0) : new Color(0, 100, 0)
);
menu.addItem(
'export project without media...',
() => {
if (this.projectName) {
this.exportProjectNoMedia(this.projectName);
} else {
this.prompt(
'Export Project As...',
name => this.exportProjectNoMedia(name),
null,
'exportProject'
);
}
},
null,
new Color(100, 0, 0)
);
menu.addItem(
'export project as cloud data...',
() => {
if (this.projectName) {
this.exportProjectAsCloudData(this.projectName);
} else {
this.prompt(
'Export Project As...',
name => this.exportProjectAsCloudData(name),
null,
'exportProject'
);
}
},
null,
new Color(100, 0, 0)
);
menu.addLine();
menu.addItem(
'open shared project from cloud...',
() => {
this.prompt(
'Author name…',
usr => {
this.prompt(
'Project name...',
prj => {
this.showMessage(
'Fetching project\nfrom the cloud...'
);
this.cloud.getPublicProject(
prj,
usr.toLowerCase(),
projectData => {
var msg;
if (
!Process.prototype.isCatchingErrors
) {
window.open(
'data:text/xml,' + projectData
);
}
this.nextSteps([
() => {
msg = this.showMessage(
'Opening project...'
);
},
() => {
this.rawOpenCloudDataString(
projectData
);
msg.destroy();
},
]);
},
this.cloudError()
);
},
null,
'project'
);
},
null,
'project'
);
},
null,
new Color(100, 0, 0)
);
}
menu.popup(world, pos);
};
IDE_Morph.prototype.settingsMenu = function () {
var menu,
stage = this.stage,
world = this.world(),
pos = this.controlBar.settingsButton.bottomLeft(),
shiftClicked = (world.currentKey === 16);
function addPreference(label, toggle, test, onHint, offHint, hide) {
var on = '\u2611 ',
off = '\u2610 ';
if (!hide || shiftClicked) {
menu.addItem(
(test ? on : off) + localize(label),
toggle,
test ? onHint : offHint,
hide ? new Color(100, 0, 0) : null
);
}
}
menu = new MenuMorph(this);
menu.addPair(
[
new SymbolMorph(
'globe',
MorphicPreferences.menuFontSize
),
localize('Language...')
],
'languageMenu'
);
menu.addItem(
'Zoom blocks...',
'userSetBlocksScale'
);
menu.addItem(
'Stage size...',
'userSetStageSize'
);
if (shiftClicked) {
menu.addItem(
'Dragging threshold...',
'userSetDragThreshold',
'specify the distance the hand has to move\n' +
'before it picks up an object',
new Color(100, 0, 0)
);
}
menu.addItem(
'Microphone resolution...',
'microphoneMenu'
);
menu.addLine();
/*
addPreference(
'JavaScript',
() => {
Process.prototype.enableJS = !Process.prototype.enableJS;
this.currentSprite.blocksCache.operators = null;
this.currentSprite.paletteCache.operators = null;
this.refreshPalette();
},
Process.prototype.enableJS,
'uncheck to disable support for\nnative JavaScript functions',
'check to support\nnative JavaScript functions'
);
*/
if (isRetinaSupported()) {
addPreference(
'Retina display support',
'toggleRetina',
isRetinaEnabled(),
'uncheck for lower resolution,\nsaves computing resources',
'check for higher resolution,\nuses more computing resources',
true
);
}
addPreference(
'Input sliders',
'toggleInputSliders',
MorphicPreferences.useSliderForInput,
'uncheck to disable\ninput sliders for\nentry fields',
'check to enable\ninput sliders for\nentry fields'
);
if (MorphicPreferences.useSliderForInput) {
addPreference(
'Execute on slider change',
'toggleSliderExecute',
ArgMorph.prototype.executeOnSliderEdit,
'uncheck to suppress\nrunning scripts\nwhen moving the slider',
'check to run\nthe edited script\nwhen moving the slider'
);
}
addPreference(
'Turbo mode',
'toggleFastTracking',
this.stage.isFastTracked,
'uncheck to run scripts\nat normal speed',
'check to prioritize\nscript execution'
);
addPreference(
'Visible stepping',
'toggleSingleStepping',
Process.prototype.enableSingleStepping,
'uncheck to turn off\nvisible stepping',
'check to turn on\n visible stepping (slow)',
false
);
addPreference(
'Log pen vectors',
() => StageMorph.prototype.enablePenLogging =
!StageMorph.prototype.enablePenLogging,
StageMorph.prototype.enablePenLogging,
'uncheck to turn off\nlogging pen vectors',
'check to turn on\nlogging pen vectors',
false
);
addPreference(
'Ternary Boolean slots',
() => BooleanSlotMorph.prototype.isTernary =
!BooleanSlotMorph.prototype.isTernary,
BooleanSlotMorph.prototype.isTernary,
'uncheck to limit\nBoolean slots to true / false',
'check to allow\nempty Boolean slots',
true
);
addPreference(
'Camera support',
'toggleCameraSupport',
CamSnapshotDialogMorph.prototype.enableCamera,
'uncheck to disable\ncamera support',
'check to enable\ncamera support',
true
);
menu.addLine(); // everything visible below is persistent
addPreference(
'Blurred shadows',
'toggleBlurredShadows',
useBlurredShadows,
'uncheck to use solid drop\nshadows and highlights',
'check to use blurred drop\nshadows and highlights',
true
);
addPreference(
'Zebra coloring',
'toggleZebraColoring',
BlockMorph.prototype.zebraContrast,
'uncheck to disable alternating\ncolors for nested block',
'check to enable alternating\ncolors for nested blocks',
true
);
addPreference(
'Dynamic input labels',
'toggleDynamicInputLabels',
SyntaxElementMorph.prototype.dynamicInputLabels,
'uncheck to disable dynamic\nlabels for variadic inputs',
'check to enable dynamic\nlabels for variadic inputs',
true
);
addPreference(
'Prefer empty slot drops',
'togglePreferEmptySlotDrops',
ScriptsMorph.prototype.isPreferringEmptySlots,
'uncheck to allow dropped\nreporters to kick out others',
'settings menu prefer empty slots hint',
true
);
addPreference(
'Long form input dialog',
'toggleLongFormInputDialog',
InputSlotDialogMorph.prototype.isLaunchingExpanded,
'uncheck to use the input\ndialog in short form',
'check to always show slot\ntypes in the input dialog'
);
addPreference(
'Plain prototype labels',
'togglePlainPrototypeLabels',
BlockLabelPlaceHolderMorph.prototype.plainLabel,
'uncheck to always show (+) symbols\nin block prototype labels',
'check to hide (+) symbols\nin block prototype labels'
);
addPreference(
'Virtual keyboard',
'toggleVirtualKeyboard',
MorphicPreferences.useVirtualKeyboard,
'uncheck to disable\nvirtual keyboard support\nfor mobile devices',
'check to enable\nvirtual keyboard support\nfor mobile devices',
true
);
addPreference(
'Clicking sound',
() => {
BlockMorph.prototype.toggleSnapSound();
if (BlockMorph.prototype.snapSound) {
this.saveSetting('click', true);
} else {
this.removeSetting('click');
}
},
BlockMorph.prototype.snapSound,
'uncheck to turn\nblock clicking\nsound off',
'check to turn\nblock clicking\nsound on'
);
addPreference(
'Animations',
() => this.isAnimating = !this.isAnimating,
this.isAnimating,
'uncheck to disable\nIDE animations',
'check to enable\nIDE animations',
true
);
addPreference(
'Cache Inputs',
() => {
BlockMorph.prototype.isCachingInputs =
!BlockMorph.prototype.isCachingInputs;
},
BlockMorph.prototype.isCachingInputs,
'uncheck to stop caching\ninputs (for debugging the evaluator)',
'check to cache inputs\nboosts recursion',
true
);
addPreference(
'Rasterize SVGs',
() => MorphicPreferences.rasterizeSVGs =
!MorphicPreferences.rasterizeSVGs,
MorphicPreferences.rasterizeSVGs,
'uncheck for smooth\nscaling of vector costumes',
'check to rasterize\nSVGs on import',
true
);
addPreference(
'Flat design',
() => {
if (MorphicPreferences.isFlat) {
return this.defaultDesign();
}
this.flatDesign();
},
MorphicPreferences.isFlat,
'uncheck for default\nGUI design',
'check for alternative\nGUI design',
false
);
addPreference(
'Nested auto-wrapping',
() => {
ScriptsMorph.prototype.enableNestedAutoWrapping =
!ScriptsMorph.prototype.enableNestedAutoWrapping;
if (ScriptsMorph.prototype.enableNestedAutoWrapping) {
this.removeSetting('autowrapping');
} else {
this.saveSetting('autowrapping', false);
}
},
ScriptsMorph.prototype.enableNestedAutoWrapping,
'uncheck to confine auto-wrapping\nto top-level block stacks',
'check to enable auto-wrapping\ninside nested block stacks',
true
);
addPreference(
'Project URLs',
() => {
this.projectsInURLs = !this.projectsInURLs;
if (this.projectsInURLs) {
this.saveSetting('longurls', true);
} else {
this.removeSetting('longurls');
}
},
this.projectsInURLs,
'uncheck to disable\nproject data in URLs',
'check to enable\nproject data in URLs',
true
);
addPreference(
'Sprite Nesting',
() => SpriteMorph.prototype.enableNesting =
!SpriteMorph.prototype.enableNesting,
SpriteMorph.prototype.enableNesting,
'uncheck to disable\nsprite composition',
'check to enable\nsprite composition',
true
);
addPreference(
'First-Class Sprites',
() => {
SpriteMorph.prototype.enableFirstClass =
!SpriteMorph.prototype.enableFirstClass;
this.currentSprite.blocksCache.sensing = null;
this.currentSprite.paletteCache.sensing = null;
this.refreshPalette();
},
SpriteMorph.prototype.enableFirstClass,
'uncheck to disable support\nfor first-class sprites',
'check to enable support\n for first-class sprite',
true
);
addPreference(
'Keyboard Editing',
() => {
ScriptsMorph.prototype.enableKeyboard =
!ScriptsMorph.prototype.enableKeyboard;
this.currentSprite.scripts.updateToolbar();
if (ScriptsMorph.prototype.enableKeyboard) {
this.removeSetting('keyboard');
} else {
this.saveSetting('keyboard', false);
}
},
ScriptsMorph.prototype.enableKeyboard,
'uncheck to disable\nkeyboard editing support',
'check to enable\nkeyboard editing support',
true
);
addPreference(
'Table support',
() => {
List.prototype.enableTables =
!List.prototype.enableTables;
if (List.prototype.enableTables) {
this.removeSetting('tables');
} else {
this.saveSetting('tables', false);
}
},
List.prototype.enableTables,
'uncheck to disable\nmulti-column list views',
'check for multi-column\nlist view support',
true
);
if (List.prototype.enableTables) {
addPreference(
'Table lines',
() => {
TableMorph.prototype.highContrast =
!TableMorph.prototype.highContrast;
if (TableMorph.prototype.highContrast) {
this.saveSetting('tableLines', true);
} else {
this.removeSetting('tableLines');
}
},
TableMorph.prototype.highContrast,
'uncheck for less contrast\nmulti-column list views',
'check for higher contrast\ntable views',
true
);
}
addPreference(
'Live coding support',
() => Process.prototype.enableLiveCoding =
!Process.prototype.enableLiveCoding,
Process.prototype.enableLiveCoding,
'EXPERIMENTAL! uncheck to disable live\ncustom control structures',
'EXPERIMENTAL! check to enable\n live custom control structures',
true
);
addPreference(
'JIT compiler support',
() => {
Process.prototype.enableCompiling =
!Process.prototype.enableCompiling;
this.currentSprite.blocksCache.operators = null;
this.currentSprite.paletteCache.operators = null;
this.refreshPalette();
},
Process.prototype.enableCompiling,
'EXPERIMENTAL! uncheck to disable live\nsupport for compiling',
'EXPERIMENTAL! check to enable\nsupport for compiling',
true
);
menu.addLine(); // everything below this line is stored in the project
addPreference(
'Thread safe scripts',
() => stage.isThreadSafe = !stage.isThreadSafe,
this.stage.isThreadSafe,
'uncheck to allow\nscript reentrance',
'check to disallow\nscript reentrance'
);
addPreference(
'Prefer smooth animations',
'toggleVariableFrameRate',
StageMorph.prototype.frameRate,
'uncheck for greater speed\nat variable frame rates',
'check for smooth, predictable\nanimations across computers',
true
);
addPreference(
'Flat line ends',
() => SpriteMorph.prototype.useFlatLineEnds =
!SpriteMorph.prototype.useFlatLineEnds,
SpriteMorph.prototype.useFlatLineEnds,
'uncheck for round ends of lines',
'check for flat ends of lines'
);
addPreference(
'Codification support',
() => {
StageMorph.prototype.enableCodeMapping =
!StageMorph.prototype.enableCodeMapping;
this.currentSprite.blocksCache.variables = null;
this.currentSprite.paletteCache.variables = null;
this.refreshPalette();
},
StageMorph.prototype.enableCodeMapping,
'uncheck to disable\nblock to text mapping features',
'check for block\nto text mapping features',
false
);
addPreference(
'Inheritance support',
() => {
StageMorph.prototype.enableInheritance =
!StageMorph.prototype.enableInheritance;
this.currentSprite.blocksCache.variables = null;
this.currentSprite.paletteCache.variables = null;
this.refreshPalette();
},
StageMorph.prototype.enableInheritance,
'uncheck to disable\nsprite inheritance features',
'check for sprite\ninheritance features',
true
);
addPreference(
'Hyper blocks support',
() => Process.prototype.enableHyperOps =
!Process.prototype.enableHyperOps,
Process.prototype.enableHyperOps,
'uncheck to disable\nusing operators on lists and tables',
'check to enable\nusing operators on lists and tables',
true
);
addPreference(
'Persist linked sublist IDs',
() => StageMorph.prototype.enableSublistIDs =
!StageMorph.prototype.enableSublistIDs,
StageMorph.prototype.enableSublistIDs,
'uncheck to disable\nsaving linked sublist identities',
'check to enable\nsaving linked sublist identities',
true
);
addPreference(
'Enable command drops in all rings',
() => RingReporterSlotMorph.prototype.enableCommandDrops =
!RingReporterSlotMorph.prototype.enableCommandDrops,
RingReporterSlotMorph.prototype.enableCommandDrops,
'uncheck to disable\ndropping commands in reporter rings',
'check to enable\ndropping commands in all rings',
true
);
menu.popup(world, pos);
};
IDE_Morph.prototype.projectMenu = function () {
var menu,
world = this.world(),
pos = this.controlBar.projectButton.bottomLeft(),
graphicsName = this.currentSprite instanceof SpriteMorph ?
'Costumes' : 'Backgrounds',
shiftClicked = (world.currentKey === 16);
menu = new MenuMorph(this);
menu.addItem('Project notes...', 'editProjectNotes');
menu.addLine();
menu.addPair('New', 'createNewProject', '^N');
menu.addPair('Open...', 'openProjectsBrowser', '^O');
menu.addPair('Save', "save", '^S');
menu.addItem('Save As...', 'saveProjectsBrowser');
menu.addLine();
menu.addItem(
'Import...',
'importLocalFile',
'file menu import hint' // looks up the actual text in the translator
);
if (shiftClicked) {
menu.addItem(
localize(
'Export project...') + ' ' + localize('(in a new window)'
),
() => {
if (this.projectName) {
this.exportProject(this.projectName, shiftClicked);
} else {
this.prompt(
'Export Project As...',
// false - override the shiftClick setting to use XML:
name => this.exportProject(name, false),
null,
'exportProject'
);
}
},
'show project data as XML\nin a new browser window',
new Color(100, 0, 0)
);
}
menu.addItem(
shiftClicked ?
'Export project as plain text...' : 'Export project...',
() => {
if (this.projectName) {
this.exportProject(this.projectName, shiftClicked);
} else {
this.prompt(
'Export Project As...',
name => this.exportProject(name, shiftClicked),
null,
'exportProject'
);
}
},
'save project data as XML\nto your downloads folder',
shiftClicked ? new Color(100, 0, 0) : null
);
if (this.stage.globalBlocks.length) {
menu.addItem(
'Export blocks...',
() => this.exportGlobalBlocks(),
'show global custom block definitions as XML' +
'\nin a new browser window'
);
menu.addItem(
'Unused blocks...',
() => this.removeUnusedBlocks(),
'find unused global custom blocks' +
'\nand remove their definitions'
);
}
menu.addItem(
'Export summary...',
() => this.exportProjectSummary(),
'open a new browser browser window\n with a summary of this project'
);
if (shiftClicked) {
menu.addItem(
'Export summary with drop-shadows...',
() => this.exportProjectSummary(true),
'open a new browser browser window' +
'\nwith a summary of this project' +
'\nwith drop-shadows on all pictures.' +
'\nnot supported by all browsers',
new Color(100, 0, 0)
);
menu.addItem(
'Export all scripts as pic...',
() => this.exportScriptsPicture(),
'show a picture of all scripts\nand block definitions',
new Color(100, 0, 0)
);
}
menu.addLine();
menu.addItem(
'Libraries...',
() => {
if (location.protocol === 'file:') {
this.importLocalFile();
return;
}
this.getURL(
this.resourceURL('libraries', 'LIBRARIES'),
txt => {
var libraries = this.parseResourceFile(txt);
new LibraryImportDialogMorph(this, libraries).popUp();
}
);
},
'Select categories of additional blocks to add to this project.'
);
menu.addItem(
localize(graphicsName) + '...',
() => {
if (location.protocol === 'file:') {
this.importLocalFile();
return;
}
this.importMedia(graphicsName);
},
'Select a costume from the media library'
);
menu.addItem(
localize('Sounds') + '...',
() => {
if (location.protocol === 'file:') {
this.importLocalFile();
return;
}
this.importMedia('Sounds');
},
'Select a sound from the media library'
);
menu.popup(world, pos);
};
IDE_Morph.prototype.resourceURL = function () {
// Take in variadic inputs that represent an a nested folder structure.
// Method can be easily overridden if running in a custom location.
// Default Snap! simply returns a path (relative to snap.html)
var args = Array.prototype.slice.call(arguments, 0);
return args.join('/');
};
IDE_Morph.prototype.getMediaList = function (dirname, callback) {
// Invoke the given callback with a list of files in a directory
// based on the contents file.
// If no callback is specified, synchronously return the list of files
// Note: Synchronous fetching has been deprecated and should be switched
var url = this.resourceURL(dirname, dirname.toUpperCase()),
async = callback instanceof Function,
data;
function alphabetically(x, y) {
return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1;
}
if (async) {
this.getURL(
url,
txt => {
var data = this.parseResourceFile(txt);
data.sort(alphabetically);
callback.call(this, data);
}
);
} else {
data = this.parseResourceFile(this.getURL(url));
data.sort(alphabetically);
return data;
}
};
IDE_Morph.prototype.parseResourceFile = function (text) {
// A Resource File lists all the files that could be loaded in a submenu
// Examples are libraries/LIBRARIES, Costumes/COSTUMES, etc
// The file format is tab-delimited, with unix newlines:
// file-name, Display Name, Help Text (optional)
var parts,
items = [];
text.split('\n').map(line =>
line.trim()
).filter(line =>
line.length > 0
).forEach(line => {
parts = line.split('\t').map(str => str.trim());
if (parts.length < 2) {return; }
items.push({
fileName: parts[0],
name: parts[1],
description: parts.length > 2 ? parts[2] : ''
});
});
return items;
};
IDE_Morph.prototype.importLocalFile = function () {
var inp = document.createElement('input'),
world = this.world();
if (this.filePicker) {
document.body.removeChild(this.filePicker);
this.filePicker = null;
}
inp.type = 'file';
inp.style.color = "transparent";
inp.style.backgroundColor = "transparent";
inp.style.border = "none";
inp.style.outline = "none";
inp.style.position = "absolute";
inp.style.top = "0px";
inp.style.left = "0px";
inp.style.width = "0px";
inp.style.height = "0px";
inp.style.display = "none";
inp.addEventListener(
"change",
() => {
document.body.removeChild(inp);
this.filePicker = null;
world.hand.processDrop(inp.files);
},
false
);
document.body.appendChild(inp);
this.filePicker = inp;
inp.click();
};
IDE_Morph.prototype.importMedia = function (folderName) {
// open a dialog box letting the user browse available "built-in"
// costumes, backgrounds or sounds
var msg = this.showMessage('Opening ' + folderName + '...');
this.getMediaList(
folderName,
items => {
msg.destroy();
this.popupMediaImportDialog(folderName, items);
}
);
};
IDE_Morph.prototype.popupMediaImportDialog = function (folderName, items) {
// private - this gets called by importMedia() and creates
// the actual dialog
var dialog = new DialogBoxMorph().withKey('import' + folderName),
frame = new ScrollFrameMorph(),
selectedIcon = null,
turtle = new SymbolMorph('turtle', 60),
myself = this,
world = this.world(),
handle;
frame.acceptsDrops = false;
frame.contents.acceptsDrops = false;
frame.color = myself.groupColor;
frame.fixLayout = nop;
dialog.labelString = folderName;
dialog.createLabel();
dialog.addBody(frame);
dialog.addButton('ok', 'Import');
dialog.addButton('cancel', 'Cancel');
dialog.ok = function () {
if (selectedIcon) {
if (selectedIcon.object instanceof Sound) {
myself.droppedAudio(
selectedIcon.object.copy().audio,
selectedIcon.labelString
);
} else if (selectedIcon.object instanceof SVG_Costume) {
myself.droppedSVG(
selectedIcon.object.contents,
selectedIcon.labelString
);
} else {
myself.droppedImage(
selectedIcon.object.contents,
selectedIcon.labelString
);
}
}
};
dialog.fixLayout = function () {
var th = fontHeight(this.titleFontSize) + this.titlePadding * 2,
x = 0,
y = 0,
fp, fw;
this.buttons.fixLayout();
this.body.setPosition(this.position().add(new Point(
this.padding,
th + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height() - this.padding * 3 - th - this.buttons.height()
));
fp = this.body.position();
fw = this.body.width();
frame.contents.children.forEach(function (icon) {
icon.setPosition(fp.add(new Point(x, y)));
x += icon.width();
if (x + icon.width() > fw) {
x = 0;
y += icon.height();
}
});
frame.contents.adjustBounds();
this.label.setCenter(this.center());
this.label.setTop(this.top() + (th - this.label.height()) / 2);
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
};
items.forEach(item => {
// Caution: creating very many thumbnails can take a long time!
var url = this.resourceURL(folderName, item.fileName),
img = new Image(),
suffix = url.slice(url.lastIndexOf('.') + 1).toLowerCase(),
isSVG = suffix === 'svg' && !MorphicPreferences.rasterizeSVGs,
isSound = contains(['wav', 'mp3'], suffix),
icon;
if (isSound) {
icon = new SoundIconMorph(new Sound(new Audio(), item.name));
} else {
icon = new CostumeIconMorph(
new Costume(turtle.getImage(), item.name)
);
}
icon.isDraggable = false;
icon.userMenu = nop;
icon.action = function () {
if (selectedIcon === icon) {return; }
var prevSelected = selectedIcon;
selectedIcon = icon;
if (prevSelected) {prevSelected.refresh(); }
};
icon.doubleClickAction = dialog.ok;
icon.query = function () {
return icon === selectedIcon;
};
frame.addContents(icon);
if (isSound) {
icon.object.audio.onloadeddata = function () {
icon.createThumbnail();
icon.fixLayout();
icon.refresh();
};
icon.object.audio.src = url;
icon.object.audio.load();
} else if (isSVG) {
img.onload = function () {
icon.object = new SVG_Costume(img, item.name);
icon.refresh();
};
this.getURL(
url,
txt => img.src = 'data:image/svg+xml;base64,' +
window.btoa(txt)
);
} else {
img.onload = function () {
var canvas = newCanvas(new Point(img.width, img.height), true);
canvas.getContext('2d').drawImage(img, 0, 0);
icon.object = new Costume(canvas, item.name);
icon.refresh();
};
img.src = url;
}
});
dialog.popUp(world);
dialog.setExtent(new Point(400, 300));
dialog.setCenter(world.center());
handle = new HandleMorph(
dialog,
300,
280,
dialog.corner,
dialog.corner
);
};
// IDE_Morph menu actions
IDE_Morph.prototype.aboutSnap = function () {
var dlg, aboutTxt, noticeTxt, creditsTxt, versions = '', translations,
module, btn1, btn2, btn3, btn4, licenseBtn, translatorsBtn,
world = this.world();
aboutTxt = 'Snap! 6.0.0 - dev -\nBuild Your Own Blocks\n\n'
+ 'Copyright \u24B8 2008-2020 Jens M\u00F6nig and '
+ 'Brian Harvey\n'
+ '[email protected], [email protected]\n\n'
+ 'Snap! is developed by the University of California, Berkeley\n'
+ ' with support from the National Science Foundation (NSF), '
+ 'MioSoft, \n'
+ 'the Communications Design Group (CDG) at SAP Labs, and the\n'
+ 'Human Advancement Research Community (HARC) at YC Research.\n'
+ 'The design of Snap! is influenced and inspired by Scratch,\n'
+ 'from the Lifelong Kindergarten group at the MIT Media Lab\n\n'
+ 'for more information see https://snap.berkeley.edu\n'
+ 'and http://scratch.mit.edu';
noticeTxt = localize('License')
+ '\n\n'
+ 'Snap! is free software: you can redistribute it and/or modify\n'
+ 'it under the terms of the GNU Affero General Public License as\n'
+ 'published by the Free Software Foundation, either version 3 of\n'
+ 'the License, or (at your option) any later version.\n\n'
+ 'This program is distributed in the hope that it will be useful,\n'
+ 'but WITHOUT ANY WARRANTY; without even the implied warranty of\n'
+ 'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n'
+ 'GNU Affero General Public License for more details.\n\n'
+ 'You should have received a copy of the\n'
+ 'GNU Affero General Public License along with this program.\n'
+ 'If not, see http://www.gnu.org/licenses/\n\n'
+ 'Want to use Snap! but scared by the open-source license?\n'
+ 'Get in touch with us, we\'ll make it work.';
creditsTxt = localize('Contributors')
+ '\n\nNathan Dinsmore: Saving/Loading, Snap-Logo Design, '
+ '\ncountless bugfixes and optimizations'
+ '\nMichael Ball: Time/Date UI, Library Import Dialog,'
+ '\ncountless bugfixes and optimizations'
+ '\nBernat Romagosa: Countless contributions'
+ '\nBartosz Leper: Retina Display Support'
+ '\nZhenlei Jia and Dariusz Dorożalski: IME text editing'
+ '\nKen Kahn: IME support and countless other contributions'
+ '\nJosep Ferràndiz: Video Motion Detection'
+ '\nJoan Guillén: Countless contributions'
+ '\nKartik Chandra: Paint Editor'
+ '\nCarles Paredes: Initial Vector Paint Editor'
+ '\n"Ava" Yuan Yuan, Dylan Servilla: Graphic Effects'
+ '\nKyle Hotchkiss: Block search design'
+ '\nBrian Broll: Many bugfixes and optimizations'
+ '\nIan Reynolds: UI Design, Event Bindings, '
+ 'Sound primitives'
+ '\nIvan Motyashov: Initial Squeak Porting'
+ '\nLucas Karahadian: Piano Keyboard Design'
+ '\nDavide Della Casa: Morphic Optimizations'
+ '\nAchal Dave: Web Audio'
+ '\nJoe Otto: Morphic Testing and Debugging';
for (module in modules) {
if (Object.prototype.hasOwnProperty.call(modules, module)) {
versions += ('\n' + module + ' (' +
modules[module] + ')');
}
}
if (versions !== '') {
versions = localize('current module versions:') + ' \n\n' +
'morphic (' + morphicVersion + ')' +
versions;
}
translations = localize('Translations') + '\n' + SnapTranslator.credits();
dlg = new DialogBoxMorph();
dlg.inform('About Snap', aboutTxt, world);
btn1 = dlg.buttons.children[0];
translatorsBtn = dlg.addButton(
() => {
dlg.body.text = translations;
dlg.body.fixLayout();
btn1.show();
btn2.show();
btn3.hide();
btn4.hide();
licenseBtn.hide();
translatorsBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'Translators...'
);
btn2 = dlg.addButton(
() => {
dlg.body.text = aboutTxt;
dlg.body.fixLayout();
btn1.show();
btn2.hide();
btn3.show();
btn4.show();
licenseBtn.show();
translatorsBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'Back...'
);
btn2.hide();
licenseBtn = dlg.addButton(
() => {
dlg.body.text = noticeTxt;
dlg.body.fixLayout();
btn1.show();
btn2.show();
btn3.hide();
btn4.hide();
licenseBtn.hide();
translatorsBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'License...'
);
btn3 = dlg.addButton(
() => {
dlg.body.text = versions;
dlg.body.fixLayout();
btn1.show();
btn2.show();
btn3.hide();
btn4.hide();
licenseBtn.hide();
translatorsBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'Modules...'
);
btn4 = dlg.addButton(
() => {
dlg.body.text = creditsTxt;
dlg.body.fixLayout();
btn1.show();
btn2.show();
translatorsBtn.show();
btn3.hide();
btn4.hide();
licenseBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'Credits...'
);
translatorsBtn.hide();
dlg.fixLayout();
};
IDE_Morph.prototype.editProjectNotes = function () {
var dialog = new DialogBoxMorph().withKey('projectNotes'),
frame = new ScrollFrameMorph(),
text = new TextMorph(this.projectNotes || ''),
size = 250,
world = this.world();
frame.padding = 6;
frame.setWidth(size);
frame.acceptsDrops = false;
frame.contents.acceptsDrops = false;
text.setWidth(size - frame.padding * 2);
text.setPosition(frame.topLeft().add(frame.padding));
text.enableSelecting();
text.isEditable = true;
frame.setHeight(size);
frame.fixLayout = nop;
frame.edge = InputFieldMorph.prototype.edge;
frame.fontSize = InputFieldMorph.prototype.fontSize;
frame.typeInPadding = InputFieldMorph.prototype.typeInPadding;
frame.contrast = InputFieldMorph.prototype.contrast;
frame.render = InputFieldMorph.prototype.render;
frame.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
frame.addContents(text);
dialog.getInput = () => text.text;
dialog.target = this;
dialog.action = (note) => this.projectNotes = note;
dialog.justDropped = () => text.edit();
dialog.labelString = 'Project Notes';
dialog.createLabel();
dialog.addBody(frame);
dialog.addButton('ok', 'OK');
dialog.addButton('cancel', 'Cancel');
dialog.fixLayout();
dialog.popUp(world);
dialog.setCenter(world.center());
text.edit();
};
IDE_Morph.prototype.newProject = function () {
this.source = this.cloud.username ? 'cloud' : null;
if (this.stage) {
this.stage.destroy();
}
if (location.hash.substr(0, 6) !== '#lang:') {
location.hash = '';
}
this.globalVariables = new VariableFrame();
this.currentSprite = new SpriteMorph(this.globalVariables);
this.sprites = new List([this.currentSprite]);
StageMorph.prototype.dimensions = new Point(480, 360);
StageMorph.prototype.hiddenPrimitives = {};
StageMorph.prototype.codeMappings = {};
StageMorph.prototype.codeHeaders = {};
StageMorph.prototype.enableCodeMapping = false;
StageMorph.prototype.enableInheritance = true;
StageMorph.prototype.enableSublistIDs = false;
StageMorph.prototype.enablePenLogging = false;
SpriteMorph.prototype.useFlatLineEnds = false;
Process.prototype.enableLiveCoding = false;
Process.prototype.enableHyperOps = true;
this.setProjectName('');
this.projectNotes = '';
this.createStage();
this.add(this.stage);
this.createCorral();
this.selectSprite(this.stage.children[0]);
this.fixLayout();
};
IDE_Morph.prototype.save = function () {
// temporary hack - only allow exporting projects to disk
// when running Snap! locally without a web server
if (location.protocol === 'file:') {
if (this.projectName) {
this.exportProject(this.projectName, false);
} else {
this.prompt(
'Export Project As...',
name => this.exportProject(name, false),
null,
'exportProject'
);
}
return;
}
if (this.source === 'examples' || this.source === 'local') {
// cannot save to examples, deprecated localStorage
this.source = null;
}
if (this.projectName) {
if (this.source === 'disk') {
this.exportProject(this.projectName);
} else if (this.source === 'cloud') {
this.saveProjectToCloud(this.projectName);
} else {
this.saveProjectsBrowser();
}
} else {
this.saveProjectsBrowser();
}
};
IDE_Morph.prototype.exportProject = function (name, plain) {
// Export project XML, saving a file to disk
// newWindow requests displaying the project in a new tab.
var menu, str, dataPrefix;
if (name) {
this.setProjectName(name);
dataPrefix = 'data:text/' + plain ? 'plain,' : 'xml,';
try {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
this.setURL('#open:' + dataPrefix + encodeURIComponent(str));
this.saveXMLAs(str, name);
menu.destroy();
this.showMessage('Exported!', 1);
} catch (err) {
if (Process.prototype.isCatchingErrors) {
this.showMessage('Export failed: ' + err);
} else {
throw err;
}
}
}
};
IDE_Morph.prototype.exportGlobalBlocks = function () {
if (this.stage.globalBlocks.length > 0) {
new BlockExportDialogMorph(
this.serializer,
this.stage.globalBlocks
).popUp(this.world());
} else {
this.inform(
'Export blocks',
'this project doesn\'t have any\n'
+ 'custom global blocks yet'
);
}
};
IDE_Morph.prototype.removeUnusedBlocks = function () {
var targets = this.sprites.asArray().concat([this.stage]),
globalBlocks = this.stage.globalBlocks,
unused = [],
isDone = false,
found;
function scan() {
return globalBlocks.filter(def => {
if (contains(unused, def)) {return false; }
return targets.every((each, trgIdx) =>
!each.usesBlockInstance(def, true, trgIdx, unused)
);
});
}
while (!isDone) {
found = scan();
if (found.length) {
unused = unused.concat(found);
} else {
isDone = true;
}
}
if (unused.length > 0) {
new BlockRemovalDialogMorph(
unused,
this.stage
).popUp(this.world());
} else {
this.inform(
'Remove unused blocks',
'there are currently no unused\n'
+ 'global custom blocks in this project'
);
}
};
IDE_Morph.prototype.exportSprite = function (sprite) {
var str = this.serializer.serialize(sprite.allParts());
str = '<sprites app="'
+ this.serializer.app
+ '" version="'
+ this.serializer.version
+ '">'
+ str
+ '</sprites>';
this.saveXMLAs(str, sprite.name);
};
IDE_Morph.prototype.exportScriptsPicture = function () {
var pics = [],
pic,
padding = 20,
w = 0,
h = 0,
y = 0,
ctx;
// collect all script pics
this.sprites.asArray().forEach(sprite => {
pics.push(sprite.getImage());
pics.push(sprite.scripts.scriptsPicture());
sprite.customBlocks.forEach(def =>
pics.push(def.scriptsPicture())
);
});
pics.push(this.stage.getImage());
pics.push(this.stage.scripts.scriptsPicture());
this.stage.customBlocks.forEach(def =>
pics.push(def.scriptsPicture())
);
// collect global block pics
this.stage.globalBlocks.forEach(def =>
pics.push(def.scriptsPicture())
);
pics = pics.filter(each => !isNil(each));
// determine dimensions of composite
pics.forEach(each => {
w = Math.max(w, each.width);
h += (each.height);
h += padding;
});
h -= padding;
pic = newCanvas(new Point(w, h));
ctx = pic.getContext('2d');
// draw all parts
pics.forEach(each => {
ctx.drawImage(each, 0, y);
y += padding;
y += each.height;
});
this.saveCanvasAs(pic, this.projectName || localize('Untitled'));
};
IDE_Morph.prototype.exportProjectSummary = function (useDropShadows) {
var html, head, meta, css, body, pname, notes, toc, globalVars,
stage = this.stage;
function addNode(tag, node, contents) {
if (!node) {node = body; }
return new XML_Element(tag, contents, node);
}
function add(contents, tag, node) {
if (!tag) {tag = 'p'; }
if (!node) {node = body; }
return new XML_Element(tag, contents, node);
}
function addImage(canvas, node, inline) {
if (!node) {node = body; }
var para = !inline ? addNode('p', node) : null,
pic = addNode('img', para || node);
pic.attributes.src = canvas.toDataURL();
return pic;
}
function addVariables(varFrame) {
var names = varFrame.names().sort(),
isFirst = true,
ul;
if (names.length) {
add(localize('Variables'), 'h3');
names.forEach(name => {
/*
addImage(
SpriteMorph.prototype.variableBlock(name).scriptPic()
);
*/
var watcher, listMorph, li, img;
if (isFirst) {
ul = addNode('ul');
isFirst = false;
}
li = addNode('li', ul);
watcher = new WatcherMorph(
name,
SpriteMorph.prototype.blockColor.variables,
varFrame,
name
);
listMorph = watcher.cellMorph.contentsMorph;
if (listMorph instanceof ListWatcherMorph) {
listMorph.expand();
}
img = addImage(watcher.fullImage(), li);
img.attributes.class = 'script';
});
}
}
function addBlocks(definitions) {
if (definitions.length) {
add(localize('Blocks'), 'h3');
SpriteMorph.prototype.categories.forEach(category => {
var isFirst = true,
ul;
definitions.forEach(def => {
var li, blockImg;
if (def.category === category) {
if (isFirst) {
add(
localize(
category[0].toUpperCase().concat(
category.slice(1)
)
),
'h4'
);
ul = addNode('ul');
isFirst = false;
}
li = addNode('li', ul);
blockImg = addImage(
def.templateInstance().scriptPic(),
li
);
blockImg.attributes.class = 'script';
def.sortedElements().forEach(script => {
var defImg = addImage(
script instanceof BlockMorph ?
script.scriptPic()
: script.fullImage(),
li
);
defImg.attributes.class = 'script';
});
}
});
});
}
}
pname = this.projectName || localize('untitled');
html = new XML_Element('html');
html.attributes.lang = SnapTranslator.language;
// html.attributes.contenteditable = 'true';
head = addNode('head', html);
meta = addNode('meta', head);
meta.attributes.charset = 'UTF-8';
if (useDropShadows) {
css = 'img {' +
'vertical-align: top;' +
'filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.5));' +
'-webkit-filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.5));' +
'-ms-filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.5));' +
'}' +
'.toc {' +
'vertical-align: middle;' +
'padding: 2px 1em 2px 1em;' +
'}';
} else {
css = 'img {' +
'vertical-align: top;' +
'}' +
'.toc {' +
'vertical-align: middle;' +
'padding: 2px 1em 2px 1em;' +
'}' +
'.sprite {' +
'border: 1px solid lightgray;' +
'}';
}
addNode('style', head, css);
add(pname, 'title', head);
body = addNode('body', html);
add(pname, 'h1');
/*
if (this.cloud.username) {
add(localize('by ') + this.cloud.username);
}
*/
if (location.hash.indexOf('#present:') === 0) {
add(location.toString(), 'a', body).attributes.href =
location.toString();
addImage(
stage.thumbnail(stage.dimensions)
).attributes.class = 'sprite';
add(this.serializer.app, 'h4');
} else {
add(this.serializer.app, 'h4');
addImage(
stage.thumbnail(stage.dimensions)
).attributes.class = 'sprite';
}
// project notes
notes = Process.prototype.reportTextSplit(this.projectNotes, 'line');
notes.asArray().forEach(paragraph => add(paragraph));
// table of contents
add(localize('Contents'), 'h4');
toc = addNode('ul');
// sprites & stage
this.sprites.asArray().concat([stage]).forEach(sprite => {
var tocEntry = addNode('li', toc),
scripts = sprite.scripts.sortedElements(),
cl = sprite.costumes.length(),
pic,
ol;
addNode('hr');
addImage(
sprite.thumbnail(new Point(40, 40)),
tocEntry,
true
).attributes.class = 'toc';
add(sprite.name, 'a', tocEntry).attributes.href = '#' + sprite.name;
add(sprite.name, 'h2').attributes.id = sprite.name;
// if (sprite instanceof SpriteMorph || sprite.costume) {
pic = addImage(
sprite.thumbnail(sprite.extent().divideBy(stage.scale))
);
pic.attributes.class = 'sprite';
if (sprite instanceof SpriteMorph) {
if (sprite.exemplar) {
addImage(
sprite.exemplar.thumbnail(new Point(40, 40)),
add(localize('Kind of') + ' ' + sprite.exemplar.name),
true
).attributes.class = 'toc';
}
if (sprite.anchor) {
addImage(
sprite.anchor.thumbnail(new Point(40, 40)),
add(localize('Part of') + ' ' + sprite.anchor.name),
true
).attributes.class = 'toc';
}
if (sprite.parts.length) {
add(localize('Parts'), 'h3');
ol = addNode('ul');
sprite.parts.forEach(part => {
var li = addNode('li', ol, part.name);
addImage(part.thumbnail(new Point(40, 40)), li, true)
.attributes.class = 'toc';
});
}
}
// costumes
if (cl > 1 || (sprite.getCostumeIdx() !== cl)) {
add(localize('Costumes'), 'h3');
ol = addNode('ol');
sprite.costumes.asArray().forEach(costume => {
var li = addNode('li', ol, costume.name);
addImage(costume.thumbnail(new Point(40, 40)), li, true)
.attributes.class = 'toc';
});
}
// sounds
if (sprite.sounds.length()) {
add(localize('Sounds'), 'h3');
ol = addNode('ol');
sprite.sounds.asArray().forEach(sound =>
add(sound.name, 'li', ol)
);
}
// variables
addVariables(sprite.variables);
// scripts
if (scripts.length) {
add(localize('Scripts'), 'h3');
scripts.forEach(script => {
var img = addImage(script instanceof BlockMorph ?
script.scriptPic()
: script.fullImage());
img.attributes.class = 'script';
});
}
// custom blocks
addBlocks(sprite.customBlocks);
});
// globals
globalVars = stage.globalVariables();
if (Object.keys(globalVars.vars).length || stage.globalBlocks.length) {
addNode('hr');
add(
localize('For all Sprites'),
'a',
addNode('li', toc)
).attributes.href = '#global';
add(localize('For all Sprites'), 'h2').attributes.id = 'global';
// variables
addVariables(globalVars);
// custom blocks
addBlocks(stage.globalBlocks);
}
this.saveFileAs(
'<!DOCTYPE html>' + html.toString(),
'text/html;charset=utf-8',
pname
);
};
IDE_Morph.prototype.openProjectString = function (str) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening project...'),
() => {
this.rawOpenProjectString(str);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenProjectString = function (str) {
this.toggleAppMode(false);
this.spriteBar.tabBar.tabTo('scripts');
StageMorph.prototype.hiddenPrimitives = {};
StageMorph.prototype.codeMappings = {};
StageMorph.prototype.codeHeaders = {};
StageMorph.prototype.enableCodeMapping = false;
StageMorph.prototype.enableInheritance = true;
StageMorph.prototype.enableSublistIDs = false;
StageMorph.prototype.enablePenLogging = false;
Process.prototype.enableLiveCoding = false;
if (Process.prototype.isCatchingErrors) {
try {
this.serializer.openProject(
this.serializer.load(str, this),
this
);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
this.serializer.openProject(
this.serializer.load(str, this),
this
);
}
this.stopFastTracking();
};
IDE_Morph.prototype.openCloudDataString = function (str) {
var msg,
size = Math.round(str.length / 1024);
this.nextSteps([
() => msg = this.showMessage('Opening project\n' + size + ' KB...'),
() => {
this.rawOpenCloudDataString(str);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenCloudDataString = function (str) {
var model;
StageMorph.prototype.hiddenPrimitives = {};
StageMorph.prototype.codeMappings = {};
StageMorph.prototype.codeHeaders = {};
StageMorph.prototype.enableCodeMapping = false;
StageMorph.prototype.enableInheritance = true;
StageMorph.prototype.enableSublistIDs = false;
StageMorph.prototype.enablePenLogging = false;
Process.prototype.enableLiveCoding = false;
if (Process.prototype.isCatchingErrors) {
try {
model = this.serializer.parse(str);
this.serializer.loadMediaModel(model.childNamed('media'));
this.serializer.openProject(
this.serializer.loadProjectModel(
model.childNamed('project'),
this,
model.attributes.remixID
),
this
);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
model = this.serializer.parse(str);
this.serializer.loadMediaModel(model.childNamed('media'));
this.serializer.openProject(
this.serializer.loadProjectModel(
model.childNamed('project'),
this,
model.attributes.remixID
),
this
);
}
this.stopFastTracking();
};
IDE_Morph.prototype.openBlocksString = function (str, name, silently) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening blocks...'),
() => {
this.rawOpenBlocksString(str, name, silently);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenBlocksString = function (str, name, silently) {
// name is optional (string), so is silently (bool)
var blocks;
if (Process.prototype.isCatchingErrors) {
try {
blocks = this.serializer.loadBlocks(str, this.stage);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
blocks = this.serializer.loadBlocks(str, this.stage);
}
if (silently) {
blocks.forEach(def => {
def.receiver = this.stage;
this.stage.globalBlocks.push(def);
this.stage.replaceDoubleDefinitionsFor(def);
});
this.flushPaletteCache();
this.refreshPalette();
this.showMessage(
'Imported Blocks Module' + (name ? ': ' + name : '') + '.',
2
);
} else {
new BlockImportDialogMorph(blocks, this.stage, name).popUp();
}
};
IDE_Morph.prototype.openSpritesString = function (str) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening sprite...'),
() => {
this.rawOpenSpritesString(str);
msg.destroy();
},
]);
};
IDE_Morph.prototype.rawOpenSpritesString = function (str) {
if (Process.prototype.isCatchingErrors) {
try {
this.serializer.loadSprites(str, this);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
this.serializer.loadSprites(str, this);
}
};
IDE_Morph.prototype.openMediaString = function (str) {
if (Process.prototype.isCatchingErrors) {
try {
this.serializer.loadMedia(str);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
this.serializer.loadMedia(str);
}
this.showMessage('Imported Media Module.', 2);
};
IDE_Morph.prototype.openScriptString = function (str) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening script...'),
() => {
this.rawOpenScriptString(str);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenScriptString = function (str) {
var xml,
script,
scripts = this.currentSprite.scripts;
if (Process.prototype.isCatchingErrors) {
try {
xml = this.serializer.parse(str, this.currentSprite);
script = this.serializer.loadScript(xml, this.currentSprite);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
xml = this.serializer.loadScript(str, this.currentSprite);
script = this.serializer.loadScript(xml, this.currentSprite);
}
script.setPosition(this.world().hand.position());
scripts.add(script);
scripts.adjustBounds();
scripts.lastDroppedBlock = script;
scripts.recordDrop(
{
origin: this.palette,
position: this.palette.center()
}
);
this.showMessage(
'Imported Script.',
2
);
};
IDE_Morph.prototype.openDataString = function (str, name, type) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening data...'),
() => {
this.rawOpenDataString(str, name, type);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenDataString = function (str, name, type) {
var data, vName, dlg,
globals = this.currentSprite.globalVariables();
function newVarName(name) {
var existing = globals.names(),
ix = name.indexOf('\('),
stem = (ix < 0) ? name : name.substring(0, ix),
count = 1,
newName = stem;
while (contains(existing, newName)) {
count += 1;
newName = stem + '(' + count + ')';
}
return newName;
}
switch (type) {
case 'csv':
data = Process.prototype.parseCSV(str);
break;
case 'json':
data = Process.prototype.parseJSON(str);
break;
default: // assume plain text
data = str;
}
vName = newVarName(name || 'data');
globals.addVar(vName);
globals.setVar(vName, data);
this.currentSprite.toggleVariableWatcher(vName, true); // global
this.flushBlocksCache('variables');
this.currentCategory = 'variables';
this.categories.children.forEach(each =>
each.refresh()
);
this.refreshPalette(true);
if (data instanceof List) {
dlg = new TableDialogMorph(data);
dlg.labelString = localize(dlg.labelString) + ': ' + vName;
dlg.createLabel();
dlg.popUp(this.world());
}
};
IDE_Morph.prototype.openProject = function (name) {
var str;
if (name) {
this.showMessage('opening project\n' + name);
this.setProjectName(name);
str = localStorage['-snap-project-' + name];
this.openProjectString(str);
this.setURL('#open:' + str);
}
};
IDE_Morph.prototype.setURL = function (str) {
// Set the URL to a project's XML contents
location.hash = this.projectsInURLs ? str : '';
};
IDE_Morph.prototype.saveFileAs = function (
contents,
fileType,
fileName
) {
/** Allow for downloading a file to a disk.
This relies the FileSaver.js library which exports saveAs()
Two utility methods saveImageAs and saveXMLAs should be used first.
*/
var blobIsSupported = false,
world = this.world(),
fileExt,
dialog;
// fileType is a <kind>/<ext>;<charset> format.
fileExt = fileType.split('/')[1].split(';')[0];
// handle text/plain as a .txt file
fileExt = '.' + (fileExt === 'plain' ? 'txt' : fileExt);
function dataURItoBlob(text, mimeType) {
var i,
data = text,
components = text.split(','),
hasTypeStr = text.indexOf('data:') === 0;
// Convert to binary data, in format Blob() can use.
if (hasTypeStr && components[0].indexOf('base64') > -1) {
text = atob(components[1]);
data = new Uint8Array(text.length);
i = text.length;
while (i--) {
data[i] = text.charCodeAt(i);
}
} else if (hasTypeStr) {
// not base64 encoded
text = text.replace(/^data:image\/.*?, */, '');
data = new Uint8Array(text.length);
i = text.length;
while (i--) {
data[i] = text.charCodeAt(i);
}
}
return new Blob([data], {type: mimeType });
}
try {
blobIsSupported = !!new Blob();
} catch (e) {}
if (blobIsSupported) {
if (!(contents instanceof Blob)) {
contents = dataURItoBlob(contents, fileType);
}
// download a file and delegate to FileSaver
// false: Do not preprend a BOM to the file.
saveAs(contents, fileName + fileExt, false);
} else {
dialog = new DialogBoxMorph();
dialog.inform(
localize('Could not export') + ' ' + fileName,
'unable to export text',
world
);
dialog.fixLayout();
}
};
IDE_Morph.prototype.saveCanvasAs = function (canvas, fileName) {
// Export a Canvas object as a PNG image
// Note: This commented out due to poor browser support.
// cavas.toBlob() is currently supported in Firefox, IE, Chrome but
// browsers prevent easily saving the generated files.
// Do not re-enable without revisiting issue #1191
// if (canvas.toBlob) {
// var myself = this;
// canvas.toBlob(function (blob) {
// myself.saveFileAs(blob, 'image/png', fileName);
// });
// return;
// }
this.saveFileAs(canvas.toDataURL(), 'image/png', fileName);
};
IDE_Morph.prototype.saveAudioAs = function (audio, fileName) {
// Export a Sound object as a WAV file
this.saveFileAs(audio.src, 'audio/wav', fileName);
};
IDE_Morph.prototype.saveXMLAs = function(xml, fileName) {
// wrapper to saving XML files with a proper type tag.
this.saveFileAs(xml, 'text/xml;chartset=utf-8', fileName);
};
IDE_Morph.prototype.switchToUserMode = function () {
var world = this.world();
world.isDevMode = false;
Process.prototype.isCatchingErrors = true;
this.controlBar.updateLabel();
this.isAutoFill = true;
this.isDraggable = false;
this.reactToWorldResize(world.bounds.copy());
this.siblings().forEach(morph => {
if (morph instanceof DialogBoxMorph) {
world.add(morph); // bring to front
} else {
morph.destroy();
}
});
this.flushBlocksCache();
this.refreshPalette();
// prevent non-DialogBoxMorphs from being dropped
// onto the World in user-mode
world.reactToDropOf = (morph) => {
if (!(morph instanceof DialogBoxMorph ||
(morph instanceof MenuMorph))) {
if (world.hand.grabOrigin) {
morph.slideBackTo(world.hand.grabOrigin);
} else {
world.hand.grab(morph);
}
}
};
this.showMessage('entering user mode', 1);
};
IDE_Morph.prototype.switchToDevMode = function () {
var world = this.world();
world.isDevMode = true;
Process.prototype.isCatchingErrors = false;
this.controlBar.updateLabel();
this.isAutoFill = false;
this.isDraggable = true;
this.setExtent(world.extent().subtract(100));
this.setPosition(world.position().add(20));
this.flushBlocksCache();
this.refreshPalette();
// enable non-DialogBoxMorphs to be dropped
// onto the World in dev-mode
delete world.reactToDropOf;
this.showMessage(
'entering development mode.\n\n'
+ 'error catching is turned off,\n'
+ 'use the browser\'s web console\n'
+ 'to see error messages.'
);
};
IDE_Morph.prototype.flushBlocksCache = function (category) {
// if no category is specified, the whole cache gets flushed
if (category) {
this.stage.blocksCache[category] = null;
this.stage.children.forEach(m => {
if (m instanceof SpriteMorph) {
m.blocksCache[category] = null;
}
});
} else {
this.stage.blocksCache = {};
this.stage.children.forEach(m => {
if (m instanceof SpriteMorph) {
m.blocksCache = {};
}
});
}
this.flushPaletteCache(category);
};
IDE_Morph.prototype.flushPaletteCache = function (category) {
// if no category is specified, the whole cache gets flushed
if (category) {
this.stage.paletteCache[category] = null;
this.stage.children.forEach(m => {
if (m instanceof SpriteMorph) {
m.paletteCache[category] = null;
}
});
} else {
this.stage.paletteCache = {};
this.stage.children.forEach(m => {
if (m instanceof SpriteMorph) {
m.paletteCache = {};
}
});
}
};
IDE_Morph.prototype.toggleZebraColoring = function () {
var scripts = [];
if (!BlockMorph.prototype.zebraContrast) {
BlockMorph.prototype.zebraContrast = 40;
} else {
BlockMorph.prototype.zebraContrast = 0;
}
// select all scripts:
this.stage.children.concat(this.stage).forEach(morph => {
if (isSnapObject(morph)) {
scripts = scripts.concat(
morph.scripts.children.filter(morph =>
morph instanceof BlockMorph
)
);
}
});
// force-update all scripts:
scripts.forEach(topBlock =>
topBlock.fixBlockColor(null, true)
);
};
IDE_Morph.prototype.toggleDynamicInputLabels = function () {
var projectData;
SyntaxElementMorph.prototype.dynamicInputLabels =
!SyntaxElementMorph.prototype.dynamicInputLabels;
if (Process.prototype.isCatchingErrors) {
try {
projectData = this.serializer.serialize(this.stage);
} catch (err) {
this.showMessage('Serialization failed: ' + err);
}
} else {
projectData = this.serializer.serialize(this.stage);
}
SpriteMorph.prototype.initBlocks();
this.spriteBar.tabBar.tabTo('scripts');
this.createCategories();
this.createCorralBar();
this.openProjectString(projectData);
};
IDE_Morph.prototype.toggleBlurredShadows = function () {
window.useBlurredShadows = !useBlurredShadows;
};
IDE_Morph.prototype.toggleLongFormInputDialog = function () {
InputSlotDialogMorph.prototype.isLaunchingExpanded =
!InputSlotDialogMorph.prototype.isLaunchingExpanded;
if (InputSlotDialogMorph.prototype.isLaunchingExpanded) {
this.saveSetting('longform', true);
} else {
this.removeSetting('longform');
}
};
IDE_Morph.prototype.togglePlainPrototypeLabels = function () {
BlockLabelPlaceHolderMorph.prototype.plainLabel =
!BlockLabelPlaceHolderMorph.prototype.plainLabel;
if (BlockLabelPlaceHolderMorph.prototype.plainLabel) {
this.saveSetting('plainprototype', true);
} else {
this.removeSetting('plainprototype');
}
};
IDE_Morph.prototype.togglePreferEmptySlotDrops = function () {
ScriptsMorph.prototype.isPreferringEmptySlots =
!ScriptsMorph.prototype.isPreferringEmptySlots;
};
IDE_Morph.prototype.toggleVirtualKeyboard = function () {
MorphicPreferences.useVirtualKeyboard =
!MorphicPreferences.useVirtualKeyboard;
};
IDE_Morph.prototype.toggleInputSliders = function () {
MorphicPreferences.useSliderForInput =
!MorphicPreferences.useSliderForInput;
};
IDE_Morph.prototype.toggleSliderExecute = function () {
ArgMorph.prototype.executeOnSliderEdit =
!ArgMorph.prototype.executeOnSliderEdit;
};
IDE_Morph.prototype.setEmbedMode = function () {
var myself = this;
this.isEmbedMode = true;
this.appModeColor = new Color(243,238,235);
this.embedOverlay = new Morph();
this.embedOverlay.color = new Color(128, 128, 128);
this.embedOverlay.alpha = 0.5;
this.embedPlayButton = new SymbolMorph('circleSolid');
this.embedPlayButton.color = new Color(64, 128, 64);
this.embedPlayButton.alpha = 0.75;
this.embedPlayButton.flag = new SymbolMorph('flag');
this.embedPlayButton.flag.color = new Color(128, 255, 128);
this.embedPlayButton.flag.alpha = 0.75;
this.embedPlayButton.add(this.embedPlayButton.flag);
this.embedPlayButton.mouseClickLeft = function () {
myself.runScripts();
myself.embedOverlay.destroy();
this.destroy();
};
this.controlBar.hide();
this.add(this.embedOverlay);
this.add(this.embedPlayButton);
this.fixLayout();
};
IDE_Morph.prototype.toggleAppMode = function (appMode) {
var world = this.world(),
elements = [
this.logo,
this.controlBar.cloudButton,
this.controlBar.projectButton,
this.controlBar.settingsButton,
this.controlBar.steppingButton,
this.controlBar.stageSizeButton,
this.paletteHandle,
this.stageHandle,
this.corral,
this.corralBar,
this.spriteEditor,
this.spriteBar,
this.palette,
this.categories
];
this.isAppMode = isNil(appMode) ? !this.isAppMode : appMode;
if (this.isAppMode) {
this.wasSingleStepping = Process.prototype.enableSingleStepping;
if (this.wasSingleStepping) {
this.toggleSingleStepping();
}
this.setColor(this.appModeColor);
this.controlBar.setColor(this.color);
this.controlBar.appModeButton.refresh();
elements.forEach(e =>
e.hide()
);
world.children.forEach(morph => {
if (morph instanceof DialogBoxMorph) {
morph.hide();
}
});
if (world.keyboardFocus instanceof ScriptFocusMorph) {
world.keyboardFocus.stopEditing();
}
} else {
if (this.wasSingleStepping && !Process.prototype.enableSingleStepping) {
this.toggleSingleStepping();
}
this.setColor(this.backgroundColor);
this.controlBar.setColor(this.frameColor);
elements.forEach(e =>
e.show()
);
this.stage.setScale(1);
// show all hidden dialogs
world.children.forEach(morph => {
if (morph instanceof DialogBoxMorph) {
morph.show();
}
});
// prevent scrollbars from showing when morph appears
world.allChildren().filter(c =>
c instanceof ScrollFrameMorph
).forEach(s =>
s.adjustScrollBars()
);
// prevent rotation and draggability controls from
// showing for the stage
if (this.currentSprite === this.stage) {
this.spriteBar.children.forEach(child => {
if (child instanceof PushButtonMorph) {
child.hide();
}
});
}
// update undrop controls
this.currentSprite.scripts.updateToolbar();
}
this.setExtent(this.world().extent());
};
IDE_Morph.prototype.toggleStageSize = function (isSmall, forcedRatio) {
var myself = this,
smallRatio = forcedRatio || 0.5,
msecs = this.isAnimating ? 100 : 0,
world = this.world(),
shiftClicked = (world.currentKey === 16),
altClicked = (world.currentKey === 18);
function toggle() {
myself.isSmallStage = isNil(isSmall) ? !myself.isSmallStage : isSmall;
}
function zoomTo(targetRatio) {
myself.isSmallStage = true;
world.animations.push(new Animation(
ratio => {
myself.stageRatio = ratio;
myself.setExtent(world.extent());
},
() => myself.stageRatio,
targetRatio - myself.stageRatio,
msecs,
null, // easing
() => {
myself.isSmallStage = (targetRatio !== 1);
myself.controlBar.stageSizeButton.refresh();
}
));
}
if (shiftClicked) {
smallRatio = SpriteIconMorph.prototype.thumbSize.x * 3 /
this.stage.dimensions.x;
if (!this.isSmallStage || (smallRatio === this.stageRatio)) {
toggle();
}
} else if (altClicked) {
smallRatio = this.width() / 2 /
this.stage.dimensions.x;
if (!this.isSmallStage || (smallRatio === this.stageRatio)) {
toggle();
}
} else {
toggle();
}
if (this.isSmallStage) {
zoomTo(smallRatio);
} else {
zoomTo(1);
}
};
IDE_Morph.prototype.setPaletteWidth = function (newWidth) {
var msecs = this.isAnimating ? 100 : 0,
world = this.world();
world.animations.push(new Animation(
newWidth => {
this.paletteWidth = newWidth;
this.setExtent(world.extent());
},
() => this.paletteWidth,
newWidth - this.paletteWidth,
msecs
));
};
IDE_Morph.prototype.createNewProject = function () {
this.confirm(
'Replace the current project with a new one?',
'New Project',
() => this.newProject()
);
};
IDE_Morph.prototype.openProjectsBrowser = function () {
if (location.protocol === 'file:') {
// bypass the project import dialog and directly pop up
// the local file picker.
// this should not be necessary, we should be able
// to access the cloud even when running Snap! locally
// to be worked on.... (jens)
this.importLocalFile();
return;
}
new ProjectDialogMorph(this, 'open').popUp();
};
IDE_Morph.prototype.saveProjectsBrowser = function () {
// temporary hack - only allow exporting projects to disk
// when running Snap! locally without a web server
if (location.protocol === 'file:') {
this.prompt(
'Export Project As...',
name => this.exportProject(name, false),
null,
'exportProject'
);
return;
}
if (this.source === 'examples') {
this.source = null; // cannot save to examples
}
new ProjectDialogMorph(this, 'save').popUp();
};
// IDE_Morph microphone settings
IDE_Morph.prototype.microphoneMenu = function () {
var menu = new MenuMorph(this),
world = this.world(),
pos = this.controlBar.settingsButton.bottomLeft(),
resolutions = ['low', 'normal', 'high', 'max'],
microphone = this.stage.microphone;
if (microphone.isReady) {
menu.addItem(
'\u2611 ' + localize('Microphone'),
() => microphone.stop()
);
menu.addLine();
}
resolutions.forEach((res, i) => {
menu.addItem(
(microphone.resolution === i + 1 ? '\u2713 ' : ' ') +
localize(res),
() => microphone.setResolution(i + 1)
);
});
menu.popup(world, pos);
};
// IDE_Morph localization
IDE_Morph.prototype.languageMenu = function () {
var menu = new MenuMorph(this),
world = this.world(),
pos = this.controlBar.settingsButton.bottomLeft();
SnapTranslator.languages().forEach(lang =>
menu.addItem(
(SnapTranslator.language === lang ? '\u2713 ' : ' ') +
SnapTranslator.languageName(lang),
() => {
this.loadNewProject = false;
this.setLanguage(lang);
}
)
);
menu.popup(world, pos);
};
IDE_Morph.prototype.setLanguage = function (lang, callback, noSave) {
var translation = document.getElementById('language'),
src = this.resourceURL('locale', 'lang-' + lang + '.js');
SnapTranslator.unload();
if (translation) {
document.head.removeChild(translation);
}
if (lang === 'en') {
return this.reflectLanguage('en', callback, noSave);
}
translation = document.createElement('script');
translation.id = 'language';
translation.onload = () => this.reflectLanguage(lang, callback, noSave);
document.head.appendChild(translation);
translation.src = src;
};
IDE_Morph.prototype.reflectLanguage = function (lang, callback, noSave) {
var projectData,
urlBar = location.hash;
SnapTranslator.language = lang;
if (!this.loadNewProject) {
if (Process.prototype.isCatchingErrors) {
try {
projectData = this.serializer.serialize(this.stage);
} catch (err) {
this.showMessage('Serialization failed: ' + err);
}
} else {
projectData = this.serializer.serialize(this.stage);
}
}
SpriteMorph.prototype.initBlocks();
this.spriteBar.tabBar.tabTo('scripts');
this.createCategories();
this.createCorralBar();
this.fixLayout();
if (this.loadNewProject) {
this.newProject();
location.hash = urlBar;
} else {
this.openProjectString(projectData);
}
if (!noSave) {
this.saveSetting('language', lang);
}
if (callback) {callback.call(this); }
};
// IDE_Morph blocks scaling
IDE_Morph.prototype.userSetBlocksScale = function () {
var scrpt,
blck,
shield,
sample,
action;
scrpt = new CommandBlockMorph();
scrpt.color = SpriteMorph.prototype.blockColor.motion;
scrpt.setSpec(localize('build'));
blck = new CommandBlockMorph();
blck.color = SpriteMorph.prototype.blockColor.sound;
blck.setSpec(localize('your own'));
scrpt.nextBlock(blck);
blck = new CommandBlockMorph();
blck.color = SpriteMorph.prototype.blockColor.operators;
blck.setSpec(localize('blocks'));
scrpt.bottomBlock().nextBlock(blck);
/*
blck = SpriteMorph.prototype.blockForSelector('doForever');
blck.inputs()[0].nestedBlock(scrpt);
*/
sample = new FrameMorph();
sample.acceptsDrops = false;
sample.color = IDE_Morph.prototype.groupColor;
sample.cachedTexture = this.scriptsPaneTexture;
sample.setExtent(new Point(250, 180));
scrpt.setPosition(sample.position().add(10));
sample.add(scrpt);
shield = new Morph();
shield.alpha = 0;
shield.setExtent(sample.extent());
shield.setPosition(sample.position());
sample.add(shield);
action = (num) => {
scrpt.blockSequence().forEach(block => {
block.setScale(num);
block.setSpec(block.blockSpec);
});
scrpt.fullChanged();
};
new DialogBoxMorph(
null,
num => this.setBlocksScale(Math.min(num, 12))
).withKey('zoomBlocks').prompt(
'Zoom blocks',
SyntaxElementMorph.prototype.scale.toString(),
this.world(),
sample, // pic
{
'normal (1x)' : 1,
'demo (1.2x)' : 1.2,
'presentation (1.4x)' : 1.4,
'big (2x)' : 2,
'huge (4x)' : 4,
'giant (8x)' : 8,
'monstrous (10x)' : 10
},
false, // read only?
true, // numeric
1, // slider min
5, // slider max
action // slider action
);
};
IDE_Morph.prototype.setBlocksScale = function (num) {
var projectData;
if (Process.prototype.isCatchingErrors) {
try {
projectData = this.serializer.serialize(this.stage);
} catch (err) {
this.showMessage('Serialization failed: ' + err);
}
} else {
projectData = this.serializer.serialize(this.stage);
}
SyntaxElementMorph.prototype.setScale(num);
CommentMorph.prototype.refreshScale();
SpriteMorph.prototype.initBlocks();
this.spriteBar.tabBar.tabTo('scripts');
this.createCategories();
this.createCorralBar();
this.fixLayout();
this.openProjectString(projectData);
this.saveSetting('zoom', num);
};
// IDE_Morph stage size manipulation
IDE_Morph.prototype.userSetStageSize = function () {
new DialogBoxMorph(
this,
this.setStageExtent,
this
).promptVector(
"Stage size",
StageMorph.prototype.dimensions,
new Point(480, 360),
'Stage width',
'Stage height',
this.world(),
null, // pic
null // msg
);
};
IDE_Morph.prototype.setStageExtent = function (aPoint) {
var myself = this,
world = this.world(),
ext = aPoint.max(new Point(240, 180));
function zoom() {
myself.step = function () {
var delta = ext.subtract(
StageMorph.prototype.dimensions
).divideBy(2);
if (delta.abs().lt(new Point(5, 5))) {
StageMorph.prototype.dimensions = ext;
delete myself.step;
} else {
StageMorph.prototype.dimensions =
StageMorph.prototype.dimensions.add(delta);
}
myself.stage.setExtent(StageMorph.prototype.dimensions);
myself.stage.clearPenTrails();
myself.fixLayout();
this.setExtent(world.extent());
};
}
this.stageRatio = 1;
this.isSmallStage = false;
this.controlBar.stageSizeButton.refresh();
this.stage.stopVideo();
this.setExtent(world.extent());
if (this.isAnimating) {
zoom();
} else {
StageMorph.prototype.dimensions = ext;
this.stage.setExtent(StageMorph.prototype.dimensions);
this.stage.clearPenTrails();
this.fixLayout();
this.setExtent(world.extent());
}
};
// IDE_Morph dragging threshold (internal feature)
IDE_Morph.prototype.userSetDragThreshold = function () {
new DialogBoxMorph(
this,
num => MorphicPreferences.grabThreshold = Math.min(
Math.max(+num, 0),
200
),
this
).prompt(
"Dragging threshold",
MorphicPreferences.grabThreshold.toString(),
this.world(),
null, // pic
null, // choices
null, // read only
true // numeric
);
};
// IDE_Morph cloud interface
IDE_Morph.prototype.initializeCloud = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.login(
user.username.toLowerCase(),
user.password,
user.choice,
(username, role, response) => {
sessionStorage.username = username;
this.source = 'cloud';
if (!isNil(response.days_left)) {
new DialogBoxMorph().inform(
'Unverified account: ' +
response.days_left +
' days left',
'You are now logged in, and your account\n' +
'is enabled for three days.\n' +
'Please use the verification link that\n' +
'was sent to your email address when you\n' +
'signed up.\n\n' +
'If you cannot find that email, please\n' +
'check your spam folder. If you still\n' +
'cannot find it, please use the "Resend\n' +
'Verification Email..." option in the cloud\n' +
'menu.\n\n' +
'You have ' + response.days_left + ' days left.',
world,
this.cloudIcon(null, new Color(0, 180, 0))
);
} else {
this.showMessage(response.message, 2);
}
},
this.cloudError()
)
).withKey('cloudlogin').promptCredentials(
'Sign in',
'login',
null,
null,
null,
null,
'stay signed in on this computer\nuntil logging out',
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.createCloudAccount = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.signup(
user.username,
user.password,
user.passwordRepeat,
user.email,
(txt, title) => new DialogBoxMorph().inform(
title,
txt + '.\n\nYou can now log in.',
world,
this.cloudIcon(null, new Color(0, 180, 0))
),
this.cloudError()
)
).withKey('cloudsignup').promptCredentials(
'Sign up',
'signup',
'https://snap.berkeley.edu/tos.html',
'Terms of Service...',
'https://snap.berkeley.edu/privacy.html',
'Privacy...',
'I have read and agree\nto the Terms of Service',
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.resetCloudPassword = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.resetPassword(
user.username,
(txt, title) => new DialogBoxMorph().inform(
title,
txt +
'\n\nAn e-mail with a link to\n' +
'reset your password\n' +
'has been sent to the address provided',
world,
this.cloudIcon(null, new Color(0, 180, 0))
),
this.cloudError()
)
).withKey('cloudresetpassword').promptCredentials(
'Reset password',
'resetPassword',
null,
null,
null,
null,
null,
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.resendVerification = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.resendVerification(
user.username,
(txt, title) => new DialogBoxMorph().inform(
title,
txt,
world,
this.cloudIcon(null, new Color(0, 180, 0))
),
this.cloudError()
)
).withKey('cloudresendverification').promptCredentials(
'Resend verification email',
'resendVerification',
null,
null,
null,
null,
null,
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.changeCloudPassword = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.changePassword(
user.oldpassword,
user.password,
user.passwordRepeat,
() => this.showMessage('password has been changed.', 2),
this.cloudError()
)
).withKey('cloudpassword').promptCredentials(
'Change Password',
'changePassword',
null,
null,
null,
null,
null,
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.logout = function () {
this.cloud.logout(
() => {
delete(sessionStorage.username);
this.showMessage('disconnected.', 2);
},
() => {
delete(sessionStorage.username);
this.showMessage('disconnected.', 2);
}
);
};
IDE_Morph.prototype.buildProjectRequest = function () {
var xml = this.serializer.serialize(this.stage),
thumbnail = normalizeCanvas(
this.stage.thumbnail(
SnapSerializer.prototype.thumbnailSize
)).toDataURL(),
body;
this.serializer.isCollectingMedia = true;
body = {
notes: this.projectNotes,
xml: xml,
media: this.hasChangedMedia ?
this.serializer.mediaXML(this.projectName) : null,
thumbnail: thumbnail,
remixID: this.stage.remixID
};
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
return body;
};
IDE_Morph.prototype.verifyProject = function (body) {
// Ensure the project is less than 10MB and serializes correctly.
var encodedBody = JSON.stringify(body);
if (encodedBody.length > Cloud.MAX_FILE_SIZE) {
new DialogBoxMorph().inform(
'Snap!Cloud - Cannot Save Project',
'The media inside this project exceeds 10 MB.\n' +
'Please reduce the size of costumes or sounds.\n',
this.world(),
this.cloudIcon(null, new Color(180, 0, 0))
);
return false;
}
// console.log(encodedBody.length);
// check if serialized data can be parsed back again
try {
this.serializer.parse(body.xml);
} catch (err) {
this.showMessage('Serialization of program data failed:\n' + err);
return false;
}
if (body.media !== null) {
try {
this.serializer.parse(body.media);
} catch (err) {
this.showMessage('Serialization of media failed:\n' + err);
return false;
}
}
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
return encodedBody.length;
};
IDE_Morph.prototype.saveProjectToCloud = function (name) {
var projectBody, projectSize;
if (name) {
this.setProjectName(name);
}
this.showMessage('Saving project\nto the cloud...');
projectBody = this.buildProjectRequest();
projectSize = this.verifyProject(projectBody);
if (!projectSize) {return; } // Invalid Projects don't return anything.
this.showMessage(
'Uploading ' + Math.round(projectSize / 1024) + ' KB...'
);
this.cloud.saveProject(
this.projectName,
projectBody,
() => this.showMessage('saved.', 2),
this.cloudError()
);
};
IDE_Morph.prototype.exportProjectMedia = function (name) {
var menu, media;
this.serializer.isCollectingMedia = true;
if (name) {
this.setProjectName(name);
try {
menu = this.showMessage('Exporting');
media = this.serializer.mediaXML(name);
this.saveXMLAs(media, this.projectName + ' media');
menu.destroy();
this.showMessage('Exported!', 1);
} catch (err) {
if (Process.prototype.isCatchingErrors) {
this.serializer.isCollectingMedia = false;
this.showMessage('Export failed: ' + err);
} else {
throw err;
}
}
}
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
// this.hasChangedMedia = false;
};
IDE_Morph.prototype.exportProjectNoMedia = function (name) {
var menu, str;
this.serializer.isCollectingMedia = true;
if (name) {
this.setProjectName(name);
if (Process.prototype.isCatchingErrors) {
try {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
this.saveXMLAs(str, this.projectName);
menu.destroy();
this.showMessage('Exported!', 1);
} catch (err) {
this.serializer.isCollectingMedia = false;
this.showMessage('Export failed: ' + err);
}
} else {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
this.saveXMLAs(str, this.projectName);
menu.destroy();
this.showMessage('Exported!', 1);
}
}
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
};
IDE_Morph.prototype.exportProjectAsCloudData = function (name) {
var menu, str, media, dta;
this.serializer.isCollectingMedia = true;
if (name) {
this.setProjectName(name);
if (Process.prototype.isCatchingErrors) {
try {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
media = this.serializer.mediaXML(name);
dta = '<snapdata>' + str + media + '</snapdata>';
this.saveXMLAs(str, this.projectName);
menu.destroy();
this.showMessage('Exported!', 1);
} catch (err) {
this.serializer.isCollectingMedia = false;
this.showMessage('Export failed: ' + err);
}
} else {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
media = this.serializer.mediaXML(name);
dta = '<snapdata>' + str + media + '</snapdata>';
this.saveXMLAs(str, this.projectName);
menu.destroy();
this.showMessage('Exported!', 1);
}
}
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
// this.hasChangedMedia = false;
};
IDE_Morph.prototype.cloudAcknowledge = function () {
return (responseText, url) => {
nop(responseText);
new DialogBoxMorph().inform(
'Cloud Connection',
'Successfully connected to:\n'
+ 'http://'
+ url,
this.world(),
this.cloudIcon(null, new Color(0, 180, 0))
);
};
};
IDE_Morph.prototype.cloudResponse = function () {
return (responseText, url) => {
var response = responseText;
if (response.length > 50) {
response = response.substring(0, 50) + '...';
}
new DialogBoxMorph().inform(
'Snap!Cloud',
'http://'
+ url + ':\n\n'
+ 'responds:\n'
+ response,
this.world(),
this.cloudIcon(null, new Color(0, 180, 0))
);
};
};
IDE_Morph.prototype.cloudError = function () {
return (responseText, url) => {
// first, try to find out an explanation for the error
// and notify the user about it,
// if none is found, show an error dialog box
var response = responseText,
// explanation = getURL('https://snap.berkeley.edu/cloudmsg.txt'),
explanation = null;
if (this.shield) {
this.shield.destroy();
this.shield = null;
}
if (explanation) {
this.showMessage(explanation);
return;
}
new DialogBoxMorph().inform(
'Snap!Cloud',
(url ? url + '\n' : '')
+ response,
this.world(),
this.cloudIcon(null, new Color(180, 0, 0))
);
};
};
IDE_Morph.prototype.cloudIcon = function (height, color) {
var clr = color || DialogBoxMorph.prototype.titleBarColor,
isFlat = MorphicPreferences.isFlat,
icon = new SymbolMorph(
isFlat ? 'cloud' : 'cloudGradient',
height || 50,
clr,
isFlat ? null : new Point(-1, -1),
clr.darker(50)
);
if (!isFlat) {
icon.addShadow(new Point(1, 1), 1, clr.lighter(95));
}
return icon;
};
IDE_Morph.prototype.setCloudURL = function () {
new DialogBoxMorph(
null,
url => this.cloud.url = url
).withKey('cloudURL').prompt(
'Cloud URL',
this.cloud.url,
this.world(),
null,
this.cloud.knownDomains
);
};
IDE_Morph.prototype.urlParameters = function () {
var parameters = location.hash.slice(location.hash.indexOf(':') + 1);
return this.cloud.parseDict(parameters);
};
IDE_Morph.prototype.hasCloudProject = function () {
var params = this.urlParameters();
return params.hasOwnProperty('Username') &&
params.hasOwnProperty('ProjectName');
};
// IDE_Morph HTTP data fetching
IDE_Morph.prototype.getURL = function (url, callback, responseType) {
// fetch the contents of a url and pass it into the specified callback.
// If no callback is specified synchronously fetch and return it
// Note: Synchronous fetching has been deprecated and should be switched
var request = new XMLHttpRequest(),
async = callback instanceof Function,
myself = this,
rsp;
if (async) {
request.responseType = responseType || 'text';
}
rsp = (!async || request.responseType === 'text') ? 'responseText'
: 'response';
try {
request.open('GET', url, async);
if (async) {
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request[rsp]) {
callback.call(
myself,
request[rsp]
);
} else {
throw new Error('unable to retrieve ' + url);
}
}
};
}
// cache-control, commented out for now
// added for Snap4Arduino but has issues with local robot servers
// request.setRequestHeader('Cache-Control', 'max-age=0');
request.send();
if (!async) {
if (request.status === 200) {
return request[rsp];
}
throw new Error('unable to retrieve ' + url);
}
} catch (err) {
myself.showMessage(err.toString());
if (async) {
callback.call(this);
} else {
return request[rsp];
}
}
};
// IDE_Morph user dialog shortcuts
IDE_Morph.prototype.showMessage = function (message, secs) {
var m = new MenuMorph(null, message),
intervalHandle;
m.popUpCenteredInWorld(this.world());
if (secs) {
intervalHandle = setInterval(function () {
m.destroy();
clearInterval(intervalHandle);
}, secs * 1000);
}
return m;
};
IDE_Morph.prototype.inform = function (title, message) {
new DialogBoxMorph().inform(
title,
localize(message),
this.world()
);
};
IDE_Morph.prototype.confirm = function (message, title, action) {
new DialogBoxMorph(null, action).askYesNo(
title,
localize(message),
this.world()
);
};
IDE_Morph.prototype.prompt = function (message, callback, choices, key) {
(new DialogBoxMorph(null, callback)).withKey(key).prompt(
message,
'',
this.world(),
null,
choices
);
};
// IDE_Morph bracing against IE
IDE_Morph.prototype.warnAboutIE = function () {
var dlg, txt;
if (this.isIE()) {
dlg = new DialogBoxMorph();
txt = new TextMorph(
'Please do not use Internet Explorer.\n' +
'Snap! runs best in a web-standards\n' +
'compliant browser',
dlg.fontSize,
dlg.fontStyle,
true,
false,
'center',
null,
null,
MorphicPreferences.isFlat ? null : new Point(1, 1),
new Color(255, 255, 255)
);
dlg.key = 'IE-Warning';
dlg.labelString = "Internet Explorer";
dlg.createLabel();
dlg.addBody(txt);
dlg.fixLayout();
dlg.popUp(this.world());
}
};
IDE_Morph.prototype.isIE = function () {
var ua = navigator.userAgent;
return ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
};
// ProjectDialogMorph ////////////////////////////////////////////////////
// ProjectDialogMorph inherits from DialogBoxMorph:
ProjectDialogMorph.prototype = new DialogBoxMorph();
ProjectDialogMorph.prototype.constructor = ProjectDialogMorph;
ProjectDialogMorph.uber = DialogBoxMorph.prototype;
// ProjectDialogMorph instance creation:
function ProjectDialogMorph(ide, label) {
this.init(ide, label);
}
ProjectDialogMorph.prototype.init = function (ide, task) {
var myself = this;
// additional properties:
this.ide = ide;
this.task = task || 'open'; // String describing what do do (open, save)
this.source = ide.source;
this.projectList = []; // [{name: , thumb: , notes:}]
this.handle = null;
this.srcBar = null;
this.nameField = null;
this.filterField = null;
this.magnifyingGlass = null;
this.listField = null;
this.preview = null;
this.notesText = null;
this.notesField = null;
this.deleteButton = null;
this.shareButton = null;
this.unshareButton = null;
this.publishButton = null;
this.unpublishButton = null;
this.recoverButton = null;
// initialize inherited properties:
ProjectDialogMorph.uber.init.call(
this,
this, // target
null, // function
null // environment
);
// override inherited properites:
this.labelString = this.task === 'save' ? 'Save Project' : 'Open Project';
this.createLabel();
this.key = 'project' + task;
// build contents
if (task === 'open' && this.source === 'disk') {
// give the user a chance to switch to another source
this.source = null;
this.buildContents();
this.projectList = [];
this.listField.hide();
this.source = 'disk';
} else {
this.buildContents();
this.onNextStep = function () { // yield to show "updating" message
myself.setSource(myself.source);
};
}
};
ProjectDialogMorph.prototype.buildContents = function () {
var thumbnail, notification;
this.addBody(new Morph());
this.body.color = this.color;
this.srcBar = new AlignmentMorph('column', this.padding / 2);
if (this.ide.cloudMsg) {
notification = new TextMorph(
this.ide.cloudMsg,
10,
null, // style
false, // bold
null, // italic
null, // alignment
null, // width
null, // font name
new Point(1, 1), // shadow offset
new Color(255, 255, 255) // shadowColor
);
notification.refresh = nop;
this.srcBar.add(notification);
}
this.addSourceButton('cloud', localize('Cloud'), 'cloud');
if (this.task === 'open') {
this.buildFilterField();
this.addSourceButton('examples', localize('Examples'), 'poster');
if (this.hasLocalProjects() || this.ide.world().currentKey === 16) {
// shift- clicked
this.addSourceButton('local', localize('Browser'), 'globe');
}
}
this.addSourceButton('disk', localize('Computer'), 'storage');
this.srcBar.fixLayout();
this.body.add(this.srcBar);
if (this.task === 'save') {
this.nameField = new InputFieldMorph(this.ide.projectName);
this.body.add(this.nameField);
}
this.listField = new ListMorph([]);
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.body.add(this.listField);
this.preview = new Morph();
this.preview.fixLayout = nop;
this.preview.edge = InputFieldMorph.prototype.edge;
this.preview.fontSize = InputFieldMorph.prototype.fontSize;
this.preview.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.preview.contrast = InputFieldMorph.prototype.contrast;
this.preview.render = function (ctx) {
InputFieldMorph.prototype.render.call(this, ctx);
if (this.texture) {
this.renderTexture(this.texture, ctx);
}
};
this.preview.renderCachedTexture = function (ctx) {
ctx.drawImage(this.cachedTexture, this.edge, this.edge);
};
this.preview.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.preview.setExtent(
this.ide.serializer.thumbnailSize.add(this.preview.edge * 2)
);
this.body.add(this.preview);
if (this.task === 'save') {
thumbnail = this.ide.stage.thumbnail(
SnapSerializer.prototype.thumbnailSize
);
this.preview.texture = null;
this.preview.cachedTexture = thumbnail;
this.preview.rerender();
}
this.notesField = new ScrollFrameMorph();
this.notesField.fixLayout = nop;
this.notesField.edge = InputFieldMorph.prototype.edge;
this.notesField.fontSize = InputFieldMorph.prototype.fontSize;
this.notesField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.notesField.contrast = InputFieldMorph.prototype.contrast;
this.notesField.render = InputFieldMorph.prototype.render;
this.notesField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.notesField.acceptsDrops = false;
this.notesField.contents.acceptsDrops = false;
if (this.task === 'open') {
this.notesText = new TextMorph('');
} else { // 'save'
this.notesText = new TextMorph(this.ide.projectNotes);
this.notesText.isEditable = true;
this.notesText.enableSelecting();
}
this.notesField.isTextLineWrapping = true;
this.notesField.padding = 3;
this.notesField.setContents(this.notesText);
this.notesField.setWidth(this.preview.width());
this.body.add(this.notesField);
if (this.task === 'open') {
this.addButton('openProject', 'Open');
this.action = 'openProject';
this.recoverButton = this.addButton('recoveryDialog', 'Recover', true);
this.recoverButton.hide();
} else { // 'save'
this.addButton('saveProject', 'Save');
this.action = 'saveProject';
}
this.shareButton = this.addButton('shareProject', 'Share', true);
this.unshareButton = this.addButton('unshareProject', 'Unshare', true);
this.shareButton.hide();
this.unshareButton.hide();
this.publishButton = this.addButton('publishProject', 'Publish', true);
this.unpublishButton = this.addButton(
'unpublishProject',
'Unpublish',
true
);
this.publishButton.hide();
this.unpublishButton.hide();
this.deleteButton = this.addButton('deleteProject', 'Delete');
this.addButton('cancel', 'Cancel');
if (notification) {
this.setExtent(new Point(500, 360).add(notification.extent()));
} else {
this.setExtent(new Point(500, 360));
}
this.fixLayout();
};
ProjectDialogMorph.prototype.popUp = function (wrrld) {
var world = wrrld || this.ide.world();
if (world) {
ProjectDialogMorph.uber.popUp.call(this, world);
this.handle = new HandleMorph(
this,
350,
330,
this.corner,
this.corner
);
}
};
// ProjectDialogMorph action buttons
ProjectDialogMorph.prototype.createButtons = function () {
if (this.buttons) {
this.buttons.destroy();
}
this.buttons = new AlignmentMorph('column', this.padding / 3);
this.buttons.bottomRow = new AlignmentMorph('row', this.padding);
this.buttons.topRow = new AlignmentMorph('row', this.padding);
this.buttons.add(this.buttons.topRow);
this.buttons.add(this.buttons.bottomRow);
this.add(this.buttons);
this.buttons.fixLayout = function () {
if (this.topRow.children.some(function (any) {
return any.isVisible;
})) {
this.topRow.show();
this.topRow.fixLayout();
} else {
this.topRow.hide();
}
this.bottomRow.fixLayout();
AlignmentMorph.prototype.fixLayout.call(this);
};
};
ProjectDialogMorph.prototype.addButton = function (action, label, topRow) {
var button = new PushButtonMorph(
this,
action || 'ok',
' ' + localize((label || 'OK')) + ' '
);
button.fontSize = this.buttonFontSize;
button.corner = this.buttonCorner;
button.edge = this.buttonEdge;
button.outline = this.buttonOutline;
button.outlineColor = this.buttonOutlineColor;
button.outlineGradient = this.buttonOutlineGradient;
button.padding = this.buttonPadding;
button.contrast = this.buttonContrast;
button.fixLayout();
if (topRow) {
this.buttons.topRow.add(button);
} else {
this.buttons.bottomRow.add(button);
}
return button;
};
// ProjectDialogMorph source buttons
ProjectDialogMorph.prototype.addSourceButton = function (
source,
label,
symbol
) {
var myself = this,
lbl1 = new StringMorph(
label,
10,
null,
true,
null,
null,
new Point(1, 1),
new Color(255, 255, 255)
),
lbl2 = new StringMorph(
label,
10,
null,
true,
null,
null,
new Point(-1, -1),
this.titleBarColor.darker(50),
new Color(255, 255, 255)
),
l1 = new Morph(),
l2 = new Morph(),
button;
lbl1.add(new SymbolMorph(
symbol,
24,
this.titleBarColor.darker(20),
new Point(1, 1),
this.titleBarColor.darker(50)
));
lbl1.children[0].setCenter(lbl1.center());
lbl1.children[0].setBottom(lbl1.top() - this.padding / 2);
l1.isCachingImage = true;
l1.cachedImage = lbl1.fullImage();
l1.bounds = lbl1.fullBounds();
lbl2.add(new SymbolMorph(
symbol,
24,
new Color(255, 255, 255),
new Point(-1, -1),
this.titleBarColor.darker(50)
));
lbl2.children[0].setCenter(lbl2.center());
lbl2.children[0].setBottom(lbl2.top() - this.padding / 2);
l2.isCachingImage = true;
l2.cachedImage = lbl2.fullImage();
l2.bounds = lbl2.fullBounds();
button = new ToggleButtonMorph(
null, //colors,
myself, // the ProjectDialog is the target
function () { // action
myself.setSource(source);
},
[l1, l2],
function () { // query
return myself.source === source;
}
);
button.corner = this.buttonCorner;
button.edge = this.buttonEdge;
button.outline = this.buttonOutline;
button.outlineColor = this.buttonOutlineColor;
button.outlineGradient = this.buttonOutlineGradient;
button.labelMinExtent = new Point(60, 0);
button.padding = this.buttonPadding;
button.contrast = this.buttonContrast;
button.pressColor = this.titleBarColor.darker(20);
button.fixLayout();
button.refresh();
this.srcBar.add(button);
};
// ProjectDialogMorph list field control
ProjectDialogMorph.prototype.fixListFieldItemColors = function () {
// remember to always fixLayout() afterwards for the changes
// to take effect
var myself = this;
this.listField.contents.children[0].alpha = 0;
this.listField.contents.children[0].children.forEach(function (item) {
item.pressColor = myself.titleBarColor.darker(20);
item.color = new Color(0, 0, 0, 0);
});
};
// ProjectDialogMorph filter field
ProjectDialogMorph.prototype.buildFilterField = function () {
var myself = this;
this.filterField = new InputFieldMorph('');
this.magnifyingGlass =
new SymbolMorph(
'magnifyingGlass',
this.filterField.height(),
this.titleBarColor.darker(50));
this.body.add(this.magnifyingGlass);
this.body.add(this.filterField);
this.filterField.reactToInput = function (evt) {
var text = this.getValue();
myself.listField.elements =
myself.projectList.filter(function (aProject) {
var name = aProject.projectname || aProject.name,
notes = aProject.notes || '';
return name.toLowerCase().indexOf(text.toLowerCase()) > -1 ||
notes.toLowerCase().indexOf(text.toLowerCase()) > -1;
});
if (myself.listField.elements.length === 0) {
myself.listField.elements.push('(no matches)');
}
myself.clearDetails();
myself.listField.buildListContents();
myself.fixListFieldItemColors();
myself.listField.adjustScrollBars();
myself.listField.scrollY(myself.listField.top());
myself.fixLayout();
};
};
// ProjectDialogMorph ops
ProjectDialogMorph.prototype.setSource = function (source) {
var myself = this,
msg;
this.source = source;
this.srcBar.children.forEach(function (button) {
button.refresh();
});
switch (this.source) {
case 'cloud':
msg = myself.ide.showMessage('Updating\nproject list...');
this.projectList = [];
myself.ide.cloud.getProjectList(
function (response) {
// Don't show cloud projects if user has since switched panes.
if (myself.source === 'cloud') {
myself.installCloudProjectList(response.projects);
}
msg.destroy();
},
function (err, lbl) {
msg.destroy();
myself.ide.cloudError().call(null, err, lbl);
}
);
return;
case 'examples':
this.projectList = this.getExamplesProjectList();
break;
case 'local':
// deprecated, only for reading
this.projectList = this.getLocalProjectList();
break;
case 'disk':
if (this.task === 'save') {
this.projectList = [];
} else {
this.destroy();
this.ide.importLocalFile();
return;
}
break;
}
this.listField.destroy();
this.listField = new ListMorph(
this.projectList,
this.projectList.length > 0 ?
function (element) {
return element.name || element;
} : null,
null,
function () {myself.ok(); }
);
if (this.source === 'disk') {
this.listField.hide();
}
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
if (this.source === 'local') {
this.listField.action = function (item) {
var src, xml;
if (item === undefined) {return; }
if (myself.nameField) {
myself.nameField.setContents(item.name || '');
}
if (myself.task === 'open') {
src = localStorage['-snap-project-' + item.name];
if (src) {
xml = myself.ide.serializer.parse(src);
myself.notesText.text = xml.childNamed('notes').contents
|| '';
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
myself.preview.texture =
xml.childNamed('thumbnail').contents || null;
myself.preview.cachedTexture = null;
myself.preview.rerender();
}
}
myself.edit();
};
} else { // 'examples'; 'cloud' is initialized elsewhere
this.listField.action = function (item) {
var src, xml;
if (item === undefined) {return; }
if (myself.nameField) {
myself.nameField.setContents(item.name || '');
}
src = myself.ide.getURL(
myself.ide.resourceURL('Examples', item.fileName)
);
xml = myself.ide.serializer.parse(src);
myself.notesText.text = xml.childNamed('notes').contents
|| '';
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
myself.preview.texture = xml.childNamed('thumbnail').contents
|| null;
myself.preview.cachedTexture = null;
myself.preview.rerender();
myself.edit();
};
}
this.body.add(this.listField);
this.shareButton.hide();
this.unshareButton.hide();
if (this.task === 'open') {
this.recoverButton.hide();
}
this.publishButton.hide();
this.unpublishButton.hide();
if (this.source === 'local') {
this.deleteButton.show();
} else { // examples
this.deleteButton.hide();
}
this.buttons.fixLayout();
this.fixLayout();
if (this.task === 'open') {
this.clearDetails();
}
};
ProjectDialogMorph.prototype.hasLocalProjects = function () {
// check and report whether old projects still exist in the
// browser's local storage, which as of v5 has been deprecated,
// so the user can recover and move them elsewhere
return Object.keys(localStorage).some(function (any) {
return any.indexOf('-snap-project-') === 0;
});
};
ProjectDialogMorph.prototype.getLocalProjectList = function () {
var stored, name, dta,
projects = [];
for (stored in localStorage) {
if (Object.prototype.hasOwnProperty.call(localStorage, stored)
&& stored.substr(0, 14) === '-snap-project-') {
name = stored.substr(14);
dta = {
name: name,
thumb: null,
notes: null
};
projects.push(dta);
}
}
projects.sort(function (x, y) {
return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1;
});
return projects;
};
ProjectDialogMorph.prototype.getExamplesProjectList = function () {
return this.ide.getMediaList('Examples');
};
ProjectDialogMorph.prototype.installCloudProjectList = function (pl) {
var myself = this;
this.projectList = pl[0] ? pl : [];
this.projectList.sort(function (x, y) {
return x.projectname.toLowerCase() < y.projectname.toLowerCase() ?
-1 : 1;
});
this.listField.destroy();
this.listField = new ListMorph(
this.projectList,
this.projectList.length > 0 ?
function (element) {
return element.projectname || element;
} : null,
[ // format: display shared project names bold
[
'bold',
function (proj) { return proj.ispublic; }
],
[
'italic',
function (proj) { return proj.ispublished; }
]
],
function () { myself.ok(); }
);
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.listField.action = function (item) {
if (item === undefined) {return; }
if (myself.nameField) {
myself.nameField.setContents(item.projectname || '');
}
if (myself.task === 'open') {
myself.notesText.text = item.notes || '';
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
myself.preview.texture = '';
myself.preview.rerender();
// we ask for the thumbnail when selecting a project
myself.ide.cloud.getThumbnail(
null, // username is implicit
item.projectname,
function (thumbnail) {
myself.preview.texture = thumbnail;
myself.preview.cachedTexture = null;
myself.preview.rerender();
});
(new SpeechBubbleMorph(new TextMorph(
localize('last changed') + '\n' + item.lastupdated,
null,
null,
null,
null,
'center'
))).popUp(
myself.world(),
myself.preview.rightCenter().add(new Point(2, 0))
);
}
if (item.ispublic) {
myself.shareButton.hide();
myself.unshareButton.show();
if (item.ispublished) {
myself.publishButton.hide();
myself.unpublishButton.show();
} else {
myself.publishButton.show();
myself.unpublishButton.hide();
}
} else {
myself.unshareButton.hide();
myself.shareButton.show();
myself.publishButton.hide();
myself.unpublishButton.hide();
}
myself.buttons.fixLayout();
myself.fixLayout();
myself.edit();
};
this.body.add(this.listField);
if (this.task === 'open') {
this.recoverButton.show();
}
this.shareButton.show();
this.unshareButton.hide();
this.deleteButton.show();
this.buttons.fixLayout();
this.fixLayout();
if (this.task === 'open') {
this.clearDetails();
}
};
ProjectDialogMorph.prototype.clearDetails = function () {
this.notesText.text = '';
this.notesText.rerender();
this.notesField.contents.adjustBounds();
this.preview.texture = null;
this.preview.cachedTexture = null;
this.preview.rerender();
};
ProjectDialogMorph.prototype.recoveryDialog = function () {
var proj = this.listField.selected;
if (!proj) {return; }
new ProjectRecoveryDialogMorph(this.ide, proj.projectname, this).popUp();
this.hide();
};
ProjectDialogMorph.prototype.openProject = function () {
var proj = this.listField.selected,
src;
if (!proj) {return; }
this.ide.source = this.source;
if (this.source === 'cloud') {
this.openCloudProject(proj);
} else if (this.source === 'examples') {
// Note "file" is a property of the parseResourceFile function.
src = this.ide.getURL(this.ide.resourceURL('Examples', proj.fileName));
this.ide.openProjectString(src);
this.destroy();
} else { // 'local'
this.ide.source = null;
this.ide.openProject(proj.name);
this.destroy();
}
};
ProjectDialogMorph.prototype.openCloudProject = function (project, delta) {
var myself = this;
myself.ide.nextSteps([
function () {
myself.ide.showMessage('Fetching project\nfrom the cloud...');
},
function () {
myself.rawOpenCloudProject(project, delta);
}
]);
};
ProjectDialogMorph.prototype.rawOpenCloudProject = function (proj, delta) {
var myself = this;
this.ide.cloud.getProject(
proj.projectname,
delta,
function (clouddata) {
myself.ide.source = 'cloud';
myself.ide.nextSteps([
function () {
myself.ide.openCloudDataString(clouddata);
}
]);
location.hash = '';
if (proj.ispublic) {
location.hash = '#present:Username=' +
encodeURIComponent(myself.ide.cloud.username) +
'&ProjectName=' +
encodeURIComponent(proj.projectname);
}
},
myself.ide.cloudError()
);
this.destroy();
};
ProjectDialogMorph.prototype.saveProject = function () {
var name = this.nameField.contents().text.text,
notes = this.notesText.text,
myself = this;
this.ide.projectNotes = notes || this.ide.projectNotes;
if (name) {
if (this.source === 'cloud') {
if (detect(
this.projectList,
function (item) {return item.projectname === name; }
)) {
this.ide.confirm(
localize(
'Are you sure you want to replace'
) + '\n"' + name + '"?',
'Replace Project',
function () {
myself.ide.setProjectName(name);
myself.saveCloudProject();
}
);
} else {
this.ide.setProjectName(name);
myself.saveCloudProject();
}
} else if (this.source === 'disk') {
this.ide.exportProject(name, false);
this.ide.source = 'disk';
this.destroy();
}
}
};
ProjectDialogMorph.prototype.saveCloudProject = function () {
this.ide.source = 'cloud';
this.ide.saveProjectToCloud();
this.destroy();
};
ProjectDialogMorph.prototype.deleteProject = function () {
var myself = this,
proj,
idx,
name;
if (this.source === 'cloud') {
proj = this.listField.selected;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to delete'
) + '\n"' + proj.projectname + '"?',
'Delete Project',
function () {
myself.ide.cloud.deleteProject(
proj.projectname,
null, // username is implicit
function () {
myself.ide.hasChangedMedia = true;
idx = myself.projectList.indexOf(proj);
myself.projectList.splice(idx, 1);
myself.installCloudProjectList(
myself.projectList
); // refresh list
},
myself.ide.cloudError()
);
}
);
}
} else { // 'local, examples'
if (this.listField.selected) {
name = this.listField.selected.name;
this.ide.confirm(
localize(
'Are you sure you want to delete'
) + '\n"' + name + '"?',
'Delete Project',
function () {
delete localStorage['-snap-project-' + name];
myself.setSource(myself.source); // refresh list
}
);
}
}
};
ProjectDialogMorph.prototype.shareProject = function () {
var myself = this,
ide = this.ide,
proj = this.listField.selected,
entry = this.listField.active;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to share'
) + '\n"' + proj.projectname + '"?',
'Share Project',
function () {
ide.showMessage('sharing\nproject...');
ide.cloud.shareProject(
proj.projectname,
null, // username is implicit
function () {
proj.ispublic = true;
myself.unshareButton.show();
myself.shareButton.hide();
myself.publishButton.show();
myself.unpublishButton.hide();
entry.label.isBold = true;
entry.label.rerender();
myself.buttons.fixLayout();
myself.rerender();
myself.ide.showMessage('shared.', 2);
// Set the Shared URL if the project is currently open
if (proj.projectname === ide.projectName) {
var usr = ide.cloud.username,
projectId = 'Username=' +
encodeURIComponent(usr.toLowerCase()) +
'&ProjectName=' +
encodeURIComponent(proj.projectname);
location.hash = 'present:' + projectId;
}
},
myself.ide.cloudError()
);
}
);
}
};
ProjectDialogMorph.prototype.unshareProject = function () {
var myself = this,
ide = this.ide,
proj = this.listField.selected,
entry = this.listField.active;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to unshare'
) + '\n"' + proj.projectname + '"?',
'Unshare Project',
function () {
ide.showMessage('unsharing\nproject...');
ide.cloud.unshareProject(
proj.projectname,
null, // username is implicit
function () {
proj.ispublic = false;
myself.shareButton.show();
myself.unshareButton.hide();
myself.publishButton.hide();
myself.unpublishButton.hide();
entry.label.isBold = false;
entry.label.isItalic = false;
entry.label.rerender();
myself.buttons.fixLayout();
myself.rerender();
myself.ide.showMessage('unshared.', 2);
if (proj.projectname === ide.projectName) {
location.hash = '';
}
},
myself.ide.cloudError()
);
}
);
}
};
ProjectDialogMorph.prototype.publishProject = function () {
var myself = this,
ide = this.ide,
proj = this.listField.selected,
entry = this.listField.active;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to publish'
) + '\n"' + proj.projectname + '"?',
'Publish Project',
function () {
ide.showMessage('publishing\nproject...');
ide.cloud.publishProject(
proj.projectname,
null, // username is implicit
function () {
proj.ispublished = true;
myself.unshareButton.show();
myself.shareButton.hide();
myself.publishButton.hide();
myself.unpublishButton.show();
entry.label.isItalic = true;
entry.label.rerender();
myself.buttons.fixLayout();
myself.rerender();
myself.ide.showMessage('published.', 2);
// Set the Shared URL if the project is currently open
if (proj.projectname === ide.projectName) {
var usr = ide.cloud.username,
projectId = 'Username=' +
encodeURIComponent(usr.toLowerCase()) +
'&ProjectName=' +
encodeURIComponent(proj.projectname);
location.hash = 'present:' + projectId;
}
},
myself.ide.cloudError()
);
}
);
}
};
ProjectDialogMorph.prototype.unpublishProject = function () {
var myself = this,
proj = this.listField.selected,
entry = this.listField.active;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to unpublish'
) + '\n"' + proj.projectname + '"?',
'Unpublish Project',
function () {
myself.ide.showMessage('unpublishing\nproject...');
myself.ide.cloud.unpublishProject(
proj.projectname,
null, // username is implicit
function () {
proj.ispublished = false;
myself.unshareButton.show();
myself.shareButton.hide();
myself.publishButton.show();
myself.unpublishButton.hide();
entry.label.isItalic = false;
entry.label.rerender();
myself.buttons.fixLayout();
myself.rerender();
myself.ide.showMessage('unpublished.', 2);
},
myself.ide.cloudError()
);
}
);
}
};
ProjectDialogMorph.prototype.edit = function () {
if (this.nameField) {
this.nameField.edit();
} else if (this.filterField) {
this.filterField.edit();
}
};
// ProjectDialogMorph layout
ProjectDialogMorph.prototype.fixLayout = function () {
var th = fontHeight(this.titleFontSize) + this.titlePadding * 2,
thin = this.padding / 2,
inputField = this.nameField || this.filterField;
if (this.buttons && (this.buttons.children.length > 0)) {
this.buttons.fixLayout();
}
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
th + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height() - this.padding * 3 - th - this.buttons.height()
));
this.srcBar.setPosition(this.body.position());
inputField.setWidth(
this.body.width() - this.srcBar.width() - this.padding * 6
);
inputField.setLeft(this.srcBar.right() + this.padding * 3);
inputField.setTop(this.srcBar.top());
this.listField.setLeft(this.srcBar.right() + this.padding);
this.listField.setWidth(
this.body.width()
- this.srcBar.width()
- this.preview.width()
- this.padding
- thin
);
this.listField.contents.children[0].adjustWidths();
this.listField.setTop(inputField.bottom() + this.padding);
this.listField.setHeight(
this.body.height() - inputField.height() - this.padding
);
if (this.magnifyingGlass) {
this.magnifyingGlass.setTop(inputField.top());
this.magnifyingGlass.setLeft(this.listField.left());
}
this.preview.setRight(this.body.right());
this.preview.setTop(inputField.bottom() + this.padding);
this.notesField.setTop(this.preview.bottom() + thin);
this.notesField.setLeft(this.preview.left());
this.notesField.setHeight(
this.body.bottom() - this.preview.bottom() - thin
);
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(this.top() + (th - this.label.height()) / 2);
}
if (this.buttons && (this.buttons.children.length > 0)) {
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// ProjectRecoveryDialogMorph /////////////////////////////////////////
// I show previous versions for a particular project and
// let users recover them.
ProjectRecoveryDialogMorph.prototype = new DialogBoxMorph();
ProjectRecoveryDialogMorph.prototype.constructor = ProjectRecoveryDialogMorph;
ProjectRecoveryDialogMorph.uber = DialogBoxMorph.prototype;
// ProjectRecoveryDialogMorph instance creation:
function ProjectRecoveryDialogMorph(ide, project, browser) {
this.init(ide, project, browser);
}
ProjectRecoveryDialogMorph.prototype.init = function (
ide,
projectName,
browser
) {
// initialize inherited properties:
ProjectRecoveryDialogMorph.uber.init.call(
this,
this, // target
null, // function
null // environment
);
this.ide = ide;
this.browser = browser;
this.key = 'recoverProject';
this.projectName = projectName;
this.versions = null;
this.handle = null;
this.listField = null;
this.preview = null;
this.notesText = null;
this.notesField = null;
this.labelString = 'Recover project';
this.createLabel();
this.buildContents();
};
ProjectRecoveryDialogMorph.prototype.buildContents = function () {
this.addBody(new Morph());
this.body.color = this.color;
this.buildListField();
this.preview = new Morph();
this.preview.fixLayout = nop;
this.preview.edge = InputFieldMorph.prototype.edge;
this.preview.fontSize = InputFieldMorph.prototype.fontSize;
this.preview.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.preview.contrast = InputFieldMorph.prototype.contrast;
this.preview.render = function (ctx) {
InputFieldMorph.prototype.render.call(this, ctx);
if (this.texture) {
this.renderTexture(this.texture, ctx);
}
};
this.preview.renderCachedTexture = function (ctx) {
ctx.drawImage(this.cachedTexture, this.edge, this.edge);
};
this.preview.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.preview.setExtent(
this.ide.serializer.thumbnailSize.add(this.preview.edge * 2)
);
this.body.add(this.preview);
this.notesField = new ScrollFrameMorph();
this.notesField.fixLayout = nop;
this.notesField.edge = InputFieldMorph.prototype.edge;
this.notesField.fontSize = InputFieldMorph.prototype.fontSize;
this.notesField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.notesField.contrast = InputFieldMorph.prototype.contrast;
this.notesField.render = InputFieldMorph.prototype.render;
this.notesField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.notesField.acceptsDrops = false;
this.notesField.contents.acceptsDrops = false;
this.notesText = new TextMorph('');
this.notesField.isTextLineWrapping = true;
this.notesField.padding = 3;
this.notesField.setContents(this.notesText);
this.notesField.setWidth(this.preview.width());
this.body.add(this.notesField);
this.addButton('recoverProject', 'Recover', true);
this.addButton('cancel', 'Cancel');
this.setExtent(new Point(360, 300));
this.fixLayout();
};
ProjectRecoveryDialogMorph.prototype.buildListField = function () {
var myself = this;
this.listField = new ListMorph([]);
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.listField.action = function (item) {
var version;
if (item === undefined) { return; }
version = detect(
myself.versions,
function (version) {
return version.lastupdated === item;
});
myself.notesText.text = version.notes || '';
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
myself.preview.texture = version.thumbnail;
myself.preview.cachedTexture = null;
myself.preview.rerender();
};
this.ide.cloud.getProjectVersionMetadata(
this.projectName,
function (versions) {
var today = new Date(),
yesterday = new Date();
yesterday.setDate(today.getDate() - 1);
myself.versions = versions;
myself.versions.forEach(function (version) {
var date = new Date(
new Date().getTime() - version.lastupdated * 1000
);
if (date.toDateString() === today.toDateString()) {
version.lastupdated = localize('Today, ') +
date.toLocaleTimeString();
} else if (date.toDateString() === yesterday.toDateString()) {
version.lastupdated = localize('Yesterday, ') +
date.toLocaleTimeString();
} else {
version.lastupdated = date.toLocaleString();
}
});
myself.listField.elements =
myself.versions.map(function (version) {
return version.lastupdated;
});
myself.clearDetails();
myself.listField.buildListContents();
myself.fixListFieldItemColors();
myself.listField.adjustScrollBars();
myself.listField.scrollY(myself.listField.top());
myself.fixLayout();
},
this.ide.cloudError()
);
this.body.add(this.listField);
};
ProjectRecoveryDialogMorph.prototype.cancel = function () {
var myself = this;
this.browser.show();
this.browser.listField.select(
detect(
this.browser.projectList,
function (item) {
return item.projectname === myself.projectName;
}
)
);
ProjectRecoveryDialogMorph.uber.cancel.call(this);
};
ProjectRecoveryDialogMorph.prototype.recoverProject = function () {
var lastupdated = this.listField.selected,
version = detect(
this.versions,
function (version) {
return version.lastupdated === lastupdated;
});
this.browser.openCloudProject(
{projectname: this.projectName},
version.delta
);
this.destroy();
};
ProjectRecoveryDialogMorph.prototype.popUp = function () {
var world = this.ide.world();
if (world) {
ProjectRecoveryDialogMorph.uber.popUp.call(this, world);
this.handle = new HandleMorph(
this,
300,
300,
this.corner,
this.corner
);
}
};
ProjectRecoveryDialogMorph.prototype.fixListFieldItemColors =
ProjectDialogMorph.prototype.fixListFieldItemColors;
ProjectRecoveryDialogMorph.prototype.clearDetails =
ProjectDialogMorph.prototype.clearDetails;
ProjectRecoveryDialogMorph.prototype.fixLayout = function () {
var titleHeight = fontHeight(this.titleFontSize) + this.titlePadding * 2,
thin = this.padding / 2;
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
titleHeight + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height()
- this.padding * 3 // top, bottom and button padding.
- titleHeight
- this.buttons.height()
));
this.listField.setWidth(
this.body.width()
- this.preview.width()
- this.padding
);
this.listField.contents.children[0].adjustWidths();
this.listField.setPosition(this.body.position());
this.listField.setHeight(this.body.height());
this.preview.setRight(this.body.right());
this.preview.setTop(this.listField.top());
this.notesField.setTop(this.preview.bottom() + thin);
this.notesField.setLeft(this.preview.left());
this.notesField.setHeight(
this.body.bottom() - this.preview.bottom() - thin
);
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(
this.top() + (titleHeight - this.label.height()) / 2
);
}
if (this.buttons) {
this.buttons.fixLayout();
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// LibraryImportDialogMorph ///////////////////////////////////////////
// I am preview dialog shown before importing a library.
// I inherit from a DialogMorph but look similar to
// ProjectDialogMorph, and BlockImportDialogMorph
LibraryImportDialogMorph.prototype = new DialogBoxMorph();
LibraryImportDialogMorph.prototype.constructor = LibraryImportDialogMorph;
LibraryImportDialogMorph.uber = DialogBoxMorph.prototype;
// LibraryImportDialogMorph instance creation:
function LibraryImportDialogMorph(ide, librariesData) {
this.init(ide, librariesData);
}
LibraryImportDialogMorph.prototype.init = function (ide, librariesData) {
// initialize inherited properties:
LibraryImportDialogMorph.uber.init.call(
this,
this, // target
null, // function
null // environment
);
this.ide = ide;
this.key = 'importLibrary';
this.librariesData = librariesData; // [{name: , fileName: , description:}]
// I contain a cached version of the libaries I have displayed,
// because users may choose to explore a library many times before
// importing.
this.libraryCache = {}; // {fileName: [blocks-array] }
this.handle = null;
this.listField = null;
this.palette = null;
this.notesText = null;
this.notesField = null;
this.labelString = 'Import library';
this.createLabel();
this.buildContents();
};
LibraryImportDialogMorph.prototype.buildContents = function () {
this.addBody(new Morph());
this.body.color = this.color;
this.initializePalette();
this.initializeLibraryDescription();
this.installLibrariesList();
this.addButton('importLibrary', 'Import');
this.addButton('cancel', 'Cancel');
this.setExtent(new Point(460, 455));
this.fixLayout();
};
LibraryImportDialogMorph.prototype.initializePalette = function () {
// I will display a scrolling list of blocks.
if (this.palette) {this.palette.destroy(); }
this.palette = new ScrollFrameMorph(
null,
null,
SpriteMorph.prototype.sliderColor
);
this.palette.color = SpriteMorph.prototype.paletteColor;
this.palette.padding = 4;
this.palette.isDraggable = false;
this.palette.acceptsDrops = false;
this.palette.contents.acceptsDrops = false;
this.body.add(this.palette);
};
LibraryImportDialogMorph.prototype.initializeLibraryDescription = function () {
if (this.notesField) {this.notesField.destroy(); }
this.notesField = new ScrollFrameMorph();
this.notesField.fixLayout = nop;
this.notesField.edge = InputFieldMorph.prototype.edge;
this.notesField.fontSize = InputFieldMorph.prototype.fontSize;
this.notesField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.notesField.contrast = InputFieldMorph.prototype.contrast;
this.notesField.render = InputFieldMorph.prototype.render;
this.notesField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.notesField.acceptsDrops = false;
this.notesField.contents.acceptsDrops = false;
this.notesText = new TextMorph('');
this.notesField.isTextLineWrapping = true;
this.notesField.padding = 3;
this.notesField.setContents(this.notesText);
this.notesField.setHeight(100);
this.body.add(this.notesField);
};
LibraryImportDialogMorph.prototype.installLibrariesList = function () {
var myself = this;
if (this.listField) {this.listField.destroy(); }
this.listField = new ListMorph(
this.librariesData,
function (element) {return element.name; },
null,
function () {myself.importLibrary(); }
);
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.listField.action = function (item) {
if (isNil(item)) {return; }
myself.notesText.text = localize(item.description || '');
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
if (myself.hasCached(item.fileName)) {
myself.displayBlocks(item.fileName);
} else {
myself.showMessage(
localize('Loading') + '\n' + localize(item.name)
);
myself.ide.getURL(
myself.ide.resourceURL('libraries', item.fileName),
function(libraryXML) {
myself.cacheLibrary(
item.fileName,
myself.ide.serializer.loadBlocks(libraryXML)
);
myself.displayBlocks(item.fileName);
}
);
}
};
this.listField.setWidth(200);
this.body.add(this.listField);
this.fixLayout();
};
LibraryImportDialogMorph.prototype.popUp = function () {
var world = this.ide.world();
if (world) {
LibraryImportDialogMorph.uber.popUp.call(this, world);
this.handle = new HandleMorph(
this,
300,
300,
this.corner,
this.corner
);
}
};
LibraryImportDialogMorph.prototype.fixListFieldItemColors =
ProjectDialogMorph.prototype.fixListFieldItemColors;
LibraryImportDialogMorph.prototype.clearDetails =
ProjectDialogMorph.prototype.clearDetails;
LibraryImportDialogMorph.prototype.fixLayout = function () {
var titleHeight = fontHeight(this.titleFontSize) + this.titlePadding * 2,
thin = this.padding / 2;
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
titleHeight + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height()
- this.padding * 3 // top, bottom and button padding.
- titleHeight
- this.buttons.height()
));
this.listField.setExtent(new Point(
200,
this.body.height()
));
this.notesField.setExtent(new Point(
this.body.width() - this.listField.width() - thin,
100
));
this.palette.setExtent(new Point(
this.notesField.width(),
this.body.height() - this.notesField.height() - thin
));
this.listField.contents.children[0].adjustWidths();
this.listField.setPosition(this.body.position());
this.palette.setPosition(this.listField.topRight().add(
new Point(thin, 0)
));
this.notesField.setPosition(this.palette.bottomLeft().add(
new Point(0, thin)
));
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(
this.top() + (titleHeight - this.label.height()) / 2
);
}
if (this.buttons) {
this.buttons.fixLayout();
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// Library Cache Utilities.
LibraryImportDialogMorph.prototype.hasCached = function (key) {
return this.libraryCache.hasOwnProperty(key);
};
LibraryImportDialogMorph.prototype.cacheLibrary = function (key, blocks) {
this.libraryCache[key] = blocks ;
};
LibraryImportDialogMorph.prototype.cachedLibrary = function (key) {
return this.libraryCache[key];
};
LibraryImportDialogMorph.prototype.importLibrary = function () {
var blocks,
ide = this.ide,
selectedLibrary = this.listField.selected.fileName,
libraryName = this.listField.selected.name;
if (this.hasCached(selectedLibrary)) {
blocks = this.cachedLibrary(selectedLibrary);
blocks.forEach(function (def) {
def.receiver = ide.stage;
ide.stage.globalBlocks.push(def);
ide.stage.replaceDoubleDefinitionsFor(def);
});
ide.showMessage(localize('Imported') + ' ' + localize(libraryName), 2);
} else {
ide.showMessage(localize('Loading') + ' ' + localize(libraryName));
ide.getURL(
ide.resourceURL('libraries', selectedLibrary),
function(libraryText) {
ide.droppedText(libraryText, libraryName);
}
);
}
this.destroy();
};
LibraryImportDialogMorph.prototype.displayBlocks = function (libraryKey) {
var x, y, blockImage, previousCategory, blockContainer,
myself = this,
padding = 4,
blocksList = this.cachedLibrary(libraryKey);
if (!blocksList.length) {return; }
// populate palette, grouped by categories.
this.initializePalette();
x = this.palette.left() + padding;
y = this.palette.top();
SpriteMorph.prototype.categories.forEach(function (category) {
blocksList.forEach(function (definition) {
if (definition.category !== category) {return; }
if (category !== previousCategory) {
y += padding;
}
previousCategory = category;
blockImage = definition.templateInstance().fullImage();
blockContainer = new Morph();
blockContainer.isCachingImage = true;
blockContainer.setExtent(
new Point(blockImage.width, blockImage.height)
);
blockContainer.cachedImage = blockImage;
blockContainer.setPosition(new Point(x, y));
myself.palette.addContents(blockContainer);
y += blockContainer.fullBounds().height() + padding;
});
});
this.palette.scrollX(padding);
this.palette.scrollY(padding);
this.fixLayout();
};
LibraryImportDialogMorph.prototype.showMessage = function (msgText) {
var msg = new MenuMorph(null, msgText);
this.initializePalette();
this.fixLayout();
msg.popUpCenteredInWorld(this.palette.contents);
};
// SpriteIconMorph ////////////////////////////////////////////////////
/*
I am a selectable element in the Sprite corral, keeping a self-updating
thumbnail of the sprite I'm respresenting, and a self-updating label
of the sprite's name (in case it is changed elsewhere)
*/
// SpriteIconMorph inherits from ToggleButtonMorph (Widgets)
SpriteIconMorph.prototype = new ToggleButtonMorph();
SpriteIconMorph.prototype.constructor = SpriteIconMorph;
SpriteIconMorph.uber = ToggleButtonMorph.prototype;
// SpriteIconMorph settings
SpriteIconMorph.prototype.thumbSize = new Point(40, 40);
SpriteIconMorph.prototype.labelShadowOffset = null;
SpriteIconMorph.prototype.labelShadowColor = null;
SpriteIconMorph.prototype.labelColor = new Color(255, 255, 255);
SpriteIconMorph.prototype.fontSize = 9;
// SpriteIconMorph instance creation:
function SpriteIconMorph(aSprite) {
this.init(aSprite);
}
SpriteIconMorph.prototype.init = function (aSprite) {
var colors, action, query, hover, myself = this;
colors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor
];
action = function () {
// make my sprite the current one
var ide = myself.parentThatIsA(IDE_Morph);
if (ide) {
ide.selectSprite(myself.object);
}
};
query = function () {
// answer true if my sprite is the current one
var ide = myself.parentThatIsA(IDE_Morph);
if (ide) {
return ide.currentSprite === myself.object;
}
return false;
};
hover = function () {
if (!aSprite.exemplar) {return null; }
return (localize('parent') + ':\n' + aSprite.exemplar.name);
};
// additional properties:
this.object = aSprite || new SpriteMorph(); // mandatory, actually
this.version = this.object.version;
this.thumbnail = null;
this.rotationButton = null; // synchronous rotation of nested sprites
// initialize inherited properties:
SpriteIconMorph.uber.init.call(
this,
colors, // color overrides, <array>: [normal, highlight, pressed]
null, // target - not needed here
action, // a toggle function
this.object.name, // label string
query, // predicate/selector
null, // environment
hover // hint
);
// override defaults and build additional components
this.isDraggable = true;
this.createThumbnail();
this.padding = 2;
this.corner = 8;
this.fixLayout();
this.fps = 1;
};
SpriteIconMorph.prototype.createThumbnail = function () {
if (this.thumbnail) {
this.thumbnail.destroy();
}
this.thumbnail = new Morph();
this.thumbnail.isCachingImage = true;
this.thumbnail.bounds.setExtent(this.thumbSize);
if (this.object instanceof SpriteMorph) { // support nested sprites
this.thumbnail.cachedImage = this.object.fullThumbnail(
this.thumbSize,
this.thumbnail.cachedImage
);
this.add(this.thumbnail);
this.createRotationButton();
} else {
this.thumbnail.cachedImage = this.object.thumbnail(
this.thumbSize,
this.thumbnail.cachedImage
);
this.add(this.thumbnail);
}
};
SpriteIconMorph.prototype.createLabel = function () {
var txt;
if (this.label) {
this.label.destroy();
}
txt = new StringMorph(
this.object.name,
this.fontSize,
this.fontStyle,
true,
false,
false,
this.labelShadowOffset,
this.labelShadowColor,
this.labelColor
);
this.label = new FrameMorph();
this.label.acceptsDrops = false;
this.label.alpha = 0;
this.label.setExtent(txt.extent());
txt.setPosition(this.label.position());
this.label.add(txt);
this.add(this.label);
};
SpriteIconMorph.prototype.createRotationButton = function () {
var button, myself = this;
if (this.rotationButton) {
this.rotationButton.destroy();
this.roationButton = null;
}
if (!this.object.anchor) {
return;
}
button = new ToggleButtonMorph(
null, // colors,
null, // target
function () {
myself.object.rotatesWithAnchor =
!myself.object.rotatesWithAnchor;
},
[
'\u2192',
'\u21BB'
],
function () { // query
return myself.object.rotatesWithAnchor;
}
);
button.corner = 8;
button.labelMinExtent = new Point(11, 11);
button.padding = 0;
button.pressColor = button.color;
// button.hint = 'rotate synchronously\nwith anchor';
button.fixLayout();
button.refresh();
this.rotationButton = button;
this.add(this.rotationButton);
};
// SpriteIconMorph stepping
SpriteIconMorph.prototype.step = function () {
if (this.version !== this.object.version) {
this.createThumbnail();
this.createLabel();
this.fixLayout();
this.version = this.object.version;
this.refresh();
}
};
// SpriteIconMorph layout
SpriteIconMorph.prototype.fixLayout = function () {
if (!this.thumbnail || !this.label) {return null; }
this.bounds.setWidth(
this.thumbnail.width()
+ this.outline * 2
+ this.edge * 2
+ this.padding * 2
);
this.bounds.setHeight(
this.thumbnail.height()
+ this.outline * 2
+ this.edge * 2
+ this.padding * 3
+ this.label.height()
);
this.thumbnail.setCenter(this.center());
this.thumbnail.setTop(
this.top() + this.outline + this.edge + this.padding
);
if (this.rotationButton) {
this.rotationButton.setTop(this.top());
this.rotationButton.setRight(this.right());
}
this.label.setWidth(
Math.min(
this.label.children[0].width(), // the actual text
this.thumbnail.width()
)
);
this.label.setCenter(this.center());
this.label.setTop(
this.thumbnail.bottom() + this.padding
);
};
// SpriteIconMorph menu
SpriteIconMorph.prototype.userMenu = function () {
var menu = new MenuMorph(this),
myself = this;
if (this.object instanceof StageMorph) {
menu.addItem(
'pic...',
function () {
var ide = myself.parentThatIsA(IDE_Morph);
ide.saveCanvasAs(
myself.object.fullImage(),
this.object.name
);
},
'open a new window\nwith a picture of the stage'
);
if (this.object.trailsLog.length) {
menu.addItem(
'svg...',
function () {myself.object.exportTrailsLogAsSVG(); },
'export pen trails\nline segments as SVG'
);
}
return menu;
}
if (!(this.object instanceof SpriteMorph)) {return null; }
menu.addItem("show", 'showSpriteOnStage');
menu.addLine();
menu.addItem("duplicate", 'duplicateSprite');
if (StageMorph.prototype.enableInheritance) {
menu.addItem("clone", 'instantiateSprite');
}
menu.addItem("delete", 'removeSprite');
menu.addLine();
if (StageMorph.prototype.enableInheritance) {
/* version that hides refactoring capability unless shift-clicked
if (this.world().currentKey === 16) { // shift-clicked
menu.addItem(
"parent...",
'chooseExemplar',
null,
new Color(100, 0, 0)
);
}
*/
menu.addItem("parent...", 'chooseExemplar');
if (this.object.exemplar) {
menu.addItem(
"release",
'releaseSprite',
'make temporary and\nhide in the sprite corral'
);
}
}
if (this.object.anchor) {
menu.addItem(
localize('detach from') + ' ' + this.object.anchor.name,
function () {myself.object.detachFromAnchor(); }
);
}
if (this.object.parts.length) {
menu.addItem(
'detach all parts',
function () {myself.object.detachAllParts(); }
);
}
menu.addItem("export...", 'exportSprite');
return menu;
};
SpriteIconMorph.prototype.duplicateSprite = function () {
var ide = this.parentThatIsA(IDE_Morph);
if (ide) {
ide.duplicateSprite(this.object);
}
};
SpriteIconMorph.prototype.instantiateSprite = function () {
var ide = this.parentThatIsA(IDE_Morph);
if (ide) {
ide.instantiateSprite(this.object);
}
};
SpriteIconMorph.prototype.removeSprite = function () {
var ide = this.parentThatIsA(IDE_Morph);
if (ide) {
ide.removeSprite(this.object);
}
};
SpriteIconMorph.prototype.exportSprite = function () {
this.object.exportSprite();
};
SpriteIconMorph.prototype.chooseExemplar = function () {
this.object.chooseExemplar();
};
SpriteIconMorph.prototype.releaseSprite = function () {
this.object.release();
};
SpriteIconMorph.prototype.showSpriteOnStage = function () {
this.object.showOnStage();
};
// SpriteIconMorph events
SpriteIconMorph.prototype.mouseDoubleClick = function () {
if (this.object instanceof SpriteMorph) {
this.object.flash();
}
};
// SpriteIconMorph drawing
SpriteIconMorph.prototype.render = function (ctx) {
// only draw the edges if I am selected
switch (this.userState) {
case 'highlight':
this.drawBackground(ctx, this.highlightColor);
break;
case 'pressed':
this.drawOutline(ctx);
this.drawBackground(ctx, this.pressColor);
this.drawEdges(
ctx,
this.pressColor,
this.pressColor.lighter(40),
this.pressColor.darker(40)
);
break;
default:
this.drawBackground(ctx, this.color);
}
};
// SpriteIconMorph drag & drop
SpriteIconMorph.prototype.prepareToBeGrabbed = function () {
var ide = this.parentThatIsA(IDE_Morph),
idx;
this.mouseClickLeft(); // select me
this.alpha = 0.5;
if (ide) {
idx = ide.sprites.asArray().indexOf(this.object);
ide.sprites.remove(idx + 1);
ide.createCorral();
ide.fixLayout();
}
};
SpriteIconMorph.prototype.justDropped = function () {
this.alpha = 1;
};
SpriteIconMorph.prototype.wantsDropOf = function (morph) {
// allow scripts & media to be copied from one sprite to another
// by drag & drop
return morph instanceof BlockMorph
|| (morph instanceof CostumeIconMorph)
|| (morph instanceof SoundIconMorph);
};
SpriteIconMorph.prototype.reactToDropOf = function (morph, hand) {
if (morph instanceof BlockMorph) {
this.copyStack(morph);
} else if (morph instanceof CostumeIconMorph) {
this.copyCostume(morph.object);
} else if (morph instanceof SoundIconMorph) {
this.copySound(morph.object);
}
this.world().add(morph);
morph.slideBackTo(hand.grabOrigin);
};
SpriteIconMorph.prototype.copyStack = function (block) {
var sprite = this.object,
dup = block.fullCopy(),
y = Math.max(sprite.scripts.children.map(function (stack) {
return stack.fullBounds().bottom();
}).concat([sprite.scripts.top()]));
dup.setPosition(new Point(sprite.scripts.left() + 20, y + 20));
sprite.scripts.add(dup);
dup.allComments().forEach(function (comment) {
comment.align(dup);
});
sprite.scripts.adjustBounds();
// delete all local custom blocks (methods) that the receiver
// doesn't understand
dup.allChildren().forEach(function (morph) {
if (morph.isCustomBlock &&
!morph.isGlobal &&
!sprite.getMethod(morph.blockSpec)
) {
morph.deleteBlock();
}
});
};
SpriteIconMorph.prototype.copyCostume = function (costume) {
var dup = costume.copy();
dup.name = this.object.newCostumeName(dup.name);
this.object.addCostume(dup);
this.object.wearCostume(dup);
};
SpriteIconMorph.prototype.copySound = function (sound) {
var dup = sound.copy();
this.object.addSound(dup.audio, dup.name);
};
// CostumeIconMorph ////////////////////////////////////////////////////
/*
I am a selectable element in the SpriteEditor's "Costumes" tab, keeping
a self-updating thumbnail of the costume I'm respresenting, and a
self-updating label of the costume's name (in case it is changed
elsewhere)
*/
// CostumeIconMorph inherits from ToggleButtonMorph (Widgets)
// ... and copies methods from SpriteIconMorph
CostumeIconMorph.prototype = new ToggleButtonMorph();
CostumeIconMorph.prototype.constructor = CostumeIconMorph;
CostumeIconMorph.uber = ToggleButtonMorph.prototype;
// CostumeIconMorph settings
CostumeIconMorph.prototype.thumbSize = new Point(80, 60);
CostumeIconMorph.prototype.labelShadowOffset = null;
CostumeIconMorph.prototype.labelShadowColor = null;
CostumeIconMorph.prototype.labelColor = new Color(255, 255, 255);
CostumeIconMorph.prototype.fontSize = 9;
// CostumeIconMorph instance creation:
function CostumeIconMorph(aCostume) {
this.init(aCostume);
}
CostumeIconMorph.prototype.init = function (aCostume) {
var colors, action, query, myself = this;
colors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor
];
action = function () {
// make my costume the current one
var ide = myself.parentThatIsA(IDE_Morph),
wardrobe = myself.parentThatIsA(WardrobeMorph);
if (ide) {
ide.currentSprite.wearCostume(myself.object);
}
if (wardrobe) {
wardrobe.updateSelection();
}
};
query = function () {
// answer true if my costume is the current one
var ide = myself.parentThatIsA(IDE_Morph);
if (ide) {
return ide.currentSprite.costume === myself.object;
}
return false;
};
// additional properties:
this.object = aCostume || new Costume(); // mandatory, actually
this.version = this.object.version;
this.thumbnail = null;
// initialize inherited properties:
CostumeIconMorph.uber.init.call(
this,
colors, // color overrides, <array>: [normal, highlight, pressed]
null, // target - not needed here
action, // a toggle function
this.object.name, // label string
query, // predicate/selector
null, // environment
null // hint
);
// override defaults and build additional components
this.isDraggable = true;
this.createThumbnail();
this.padding = 2;
this.corner = 8;
this.fixLayout();
this.fps = 1;
};
CostumeIconMorph.prototype.createThumbnail = function () {
var txt;
SpriteIconMorph.prototype.createThumbnail.call(this);
if (this.object instanceof SVG_Costume) {
txt = new StringMorph(
'svg',
this.fontSize * 0.8,
this.fontStyle,
false,
false,
false,
this.labelShadowOffset,
this.labelShadowColor,
this.labelColor
);
txt.setBottom(this.thumbnail.bottom());
this.thumbnail.add(txt);
}
};
CostumeIconMorph.prototype.createLabel
= SpriteIconMorph.prototype.createLabel;
// CostumeIconMorph stepping
CostumeIconMorph.prototype.step
= SpriteIconMorph.prototype.step;
// CostumeIconMorph layout
CostumeIconMorph.prototype.fixLayout
= SpriteIconMorph.prototype.fixLayout;
// CostumeIconMorph menu
CostumeIconMorph.prototype.userMenu = function () {
var menu = new MenuMorph(this);
if (!(this.object instanceof Costume)) {return null; }
menu.addItem("edit", "editCostume");
if (this.world().currentKey === 16) { // shift clicked
menu.addItem(
'edit rotation point only...',
'editRotationPointOnly',
null,
new Color(100, 0, 0)
);
}
menu.addItem("rename", "renameCostume");
menu.addLine();
menu.addItem("duplicate", "duplicateCostume");
menu.addItem("delete", "removeCostume");
menu.addLine();
menu.addItem("export", "exportCostume");
return menu;
};
CostumeIconMorph.prototype.editCostume = function () {
this.disinherit();
if (this.object instanceof SVG_Costume && this.object.shapes.length === 0) {
try {
this.object.parseShapes();
} catch (e) {
this.editRotationPointOnly();
return;
}
}
this.object.edit(
this.world(),
this.parentThatIsA(IDE_Morph),
false // not a new costume, retain existing rotation center
);
};
CostumeIconMorph.prototype.editRotationPointOnly = function () {
var ide = this.parentThatIsA(IDE_Morph);
this.object.editRotationPointOnly(this.world());
ide.hasChangedMedia = true;
};
CostumeIconMorph.prototype.renameCostume = function () {
this.disinherit();
var costume = this.object,
wardrobe = this.parentThatIsA(WardrobeMorph),
ide = this.parentThatIsA(IDE_Morph);
new DialogBoxMorph(
null,
function (answer) {
if (answer && (answer !== costume.name)) {
costume.name = wardrobe.sprite.newCostumeName(
answer,
costume
);
costume.version = Date.now();
ide.hasChangedMedia = true;
}
}
).prompt(
this.currentSprite instanceof SpriteMorph ?
'rename costume' : 'rename background',
costume.name,
this.world()
);
};
CostumeIconMorph.prototype.duplicateCostume = function () {
var wardrobe = this.parentThatIsA(WardrobeMorph),
ide = this.parentThatIsA(IDE_Morph),
newcos = this.object.copy();
newcos.name = wardrobe.sprite.newCostumeName(newcos.name);
wardrobe.sprite.addCostume(newcos);
wardrobe.updateList();
if (ide) {
ide.currentSprite.wearCostume(newcos);
}
};
CostumeIconMorph.prototype.removeCostume = function () {
var wardrobe = this.parentThatIsA(WardrobeMorph),
idx = this.parent.children.indexOf(this),
off = CamSnapshotDialogMorph.prototype.enableCamera ? 3 : 2,
ide = this.parentThatIsA(IDE_Morph);
wardrobe.removeCostumeAt(idx - off); // ignore paintbrush and camera buttons
if (ide.currentSprite.costume === this.object) {
ide.currentSprite.wearCostume(null);
}
};
CostumeIconMorph.prototype.exportCostume = function () {
var ide = this.parentThatIsA(IDE_Morph);
if (this.object instanceof SVG_Costume) {
// don't show SVG costumes in a new tab (shows text)
ide.saveFileAs(this.object.contents.src, 'text/svg', this.object.name);
} else { // rasterized Costume
ide.saveCanvasAs(this.object.contents, this.object.name);
}
};
// CostumeIconMorph drawing
CostumeIconMorph.prototype.render
= SpriteIconMorph.prototype.render;
// CostumeIconMorph inheritance
CostumeIconMorph.prototype.disinherit = function () {
var wardrobe = this.parentThatIsA(WardrobeMorph),
idx = this.parent.children.indexOf(this);
if (wardrobe.sprite.inheritsAttribute('costumes')) {
wardrobe.sprite.shadowAttribute('costumes');
this.object = wardrobe.sprite.costumes.at(idx - 3);
}
};
// CostumeIconMorph drag & drop
CostumeIconMorph.prototype.prepareToBeGrabbed = function () {
this.disinherit();
this.mouseClickLeft(); // select me
this.removeCostume();
};
// TurtleIconMorph ////////////////////////////////////////////////////
/*
I am a selectable element in the SpriteEditor's "Costumes" tab, keeping
a thumbnail of the sprite's or stage's default "Turtle" costume.
*/
// TurtleIconMorph inherits from ToggleButtonMorph (Widgets)
// ... and copies methods from SpriteIconMorph
TurtleIconMorph.prototype = new ToggleButtonMorph();
TurtleIconMorph.prototype.constructor = TurtleIconMorph;
TurtleIconMorph.uber = ToggleButtonMorph.prototype;
// TurtleIconMorph settings
TurtleIconMorph.prototype.thumbSize = new Point(80, 60);
TurtleIconMorph.prototype.labelShadowOffset = null;
TurtleIconMorph.prototype.labelShadowColor = null;
TurtleIconMorph.prototype.labelColor = new Color(255, 255, 255);
TurtleIconMorph.prototype.fontSize = 9;
// TurtleIconMorph instance creation:
function TurtleIconMorph(aSpriteOrStage) {
this.init(aSpriteOrStage);
}
TurtleIconMorph.prototype.init = function (aSpriteOrStage) {
var colors, action, query, myself = this;
colors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor
];
action = function () {
// make my costume the current one
var ide = myself.parentThatIsA(IDE_Morph),
wardrobe = myself.parentThatIsA(WardrobeMorph);
if (ide) {
ide.currentSprite.wearCostume(null);
}
if (wardrobe) {
wardrobe.updateSelection();
}
};
query = function () {
// answer true if my costume is the current one
var ide = myself.parentThatIsA(IDE_Morph);
if (ide) {
return ide.currentSprite.costume === null;
}
return false;
};
// additional properties:
this.object = aSpriteOrStage; // mandatory, actually
this.version = this.object.version;
this.thumbnail = null;
// initialize inherited properties:
TurtleIconMorph.uber.init.call(
this,
colors, // color overrides, <array>: [normal, highlight, pressed]
null, // target - not needed here
action, // a toggle function
'default', // label string
query, // predicate/selector
null, // environment
null // hint
);
// override defaults and build additional components
this.isDraggable = false;
this.createThumbnail();
this.padding = 2;
this.corner = 8;
this.fixLayout();
};
TurtleIconMorph.prototype.createThumbnail = function () {
var isFlat = MorphicPreferences.isFlat;
if (this.thumbnail) {
this.thumbnail.destroy();
}
if (this.object instanceof SpriteMorph) {
this.thumbnail = new SymbolMorph(
'turtle',
this.thumbSize.y,
this.labelColor,
isFlat ? null : new Point(-1, -1),
new Color(0, 0, 0)
);
} else {
this.thumbnail = new SymbolMorph(
'stage',
this.thumbSize.y,
this.labelColor,
isFlat ? null : new Point(-1, -1),
new Color(0, 0, 0)
);
}
this.add(this.thumbnail);
};
TurtleIconMorph.prototype.createLabel = function () {
var txt;
if (this.label) {
this.label.destroy();
}
txt = new StringMorph(
localize(
this.object instanceof SpriteMorph ? 'Turtle' : 'Empty'
),
this.fontSize,
this.fontStyle,
true,
false,
false,
this.labelShadowOffset,
this.labelShadowColor,
this.labelColor
);
this.label = new FrameMorph();
this.label.acceptsDrops = false;
this.label.alpha = 0;
this.label.setExtent(txt.extent());
txt.setPosition(this.label.position());
this.label.add(txt);
this.add(this.label);
};
// TurtleIconMorph layout
TurtleIconMorph.prototype.fixLayout
= SpriteIconMorph.prototype.fixLayout;
// TurtleIconMorph drawing
TurtleIconMorph.prototype.render
= SpriteIconMorph.prototype.render;
// TurtleIconMorph user menu
TurtleIconMorph.prototype.userMenu = function () {
var myself = this,
menu = new MenuMorph(this, 'pen'),
on = '\u25CF',
off = '\u25CB';
if (this.object instanceof StageMorph) {
return null;
}
menu.addItem(
(this.object.penPoint === 'tip' ? on : off) + ' ' + localize('tip'),
function () {
myself.object.penPoint = 'tip';
myself.object.changed();
myself.object.fixLayout();
myself.object.rerender();
}
);
menu.addItem(
(this.object.penPoint === 'middle' ? on : off) + ' ' + localize(
'middle'
),
function () {
myself.object.penPoint = 'middle';
myself.object.changed();
myself.object.fixLayout();
myself.object.rerender();
}
);
return menu;
};
// WardrobeMorph ///////////////////////////////////////////////////////
// I am a watcher on a sprite's costume list
// WardrobeMorph inherits from ScrollFrameMorph
WardrobeMorph.prototype = new ScrollFrameMorph();
WardrobeMorph.prototype.constructor = WardrobeMorph;
WardrobeMorph.uber = ScrollFrameMorph.prototype;
// WardrobeMorph settings
// ... to follow ...
// WardrobeMorph instance creation:
function WardrobeMorph(aSprite, sliderColor) {
this.init(aSprite, sliderColor);
}
WardrobeMorph.prototype.init = function (aSprite, sliderColor) {
// additional properties
this.sprite = aSprite || new SpriteMorph();
this.costumesVersion = null;
this.spriteVersion = null;
// initialize inherited properties
WardrobeMorph.uber.init.call(this, null, null, sliderColor);
// configure inherited properties
this.fps = 2;
this.updateList();
};
// Wardrobe updating
WardrobeMorph.prototype.updateList = function () {
var myself = this,
x = this.left() + 5,
y = this.top() + 5,
padding = 4,
toolsPadding = 5,
oldPos = this.contents.position(),
icon,
txt,
paintbutton,
cambutton;
this.changed();
this.contents.destroy();
this.contents = new FrameMorph(this);
this.contents.acceptsDrops = false;
this.contents.reactToDropOf = function (icon) {
myself.reactToDropOf(icon);
};
this.addBack(this.contents);
icon = new TurtleIconMorph(this.sprite);
icon.setPosition(new Point(x, y));
myself.addContents(icon);
y = icon.bottom() + padding;
paintbutton = new PushButtonMorph(
this,
"paintNew",
new SymbolMorph("brush", 15)
);
paintbutton.padding = 0;
paintbutton.corner = 12;
paintbutton.color = IDE_Morph.prototype.groupColor;
paintbutton.highlightColor = IDE_Morph.prototype.frameColor.darker(50);
paintbutton.pressColor = paintbutton.highlightColor;
paintbutton.labelMinExtent = new Point(36, 18);
paintbutton.labelShadowOffset = new Point(-1, -1);
paintbutton.labelShadowColor = paintbutton.highlightColor;
paintbutton.labelColor = TurtleIconMorph.prototype.labelColor;
paintbutton.contrast = this.buttonContrast;
paintbutton.hint = "Paint a new costume";
paintbutton.setPosition(new Point(x, y));
paintbutton.fixLayout();
paintbutton.setCenter(icon.center());
paintbutton.setLeft(icon.right() + padding * 4);
this.addContents(paintbutton);
if (CamSnapshotDialogMorph.prototype.enableCamera) {
cambutton = new PushButtonMorph(
this,
"newFromCam",
new SymbolMorph("camera", 15)
);
cambutton.padding = 0;
cambutton.corner = 12;
cambutton.color = IDE_Morph.prototype.groupColor;
cambutton.highlightColor = IDE_Morph.prototype.frameColor.darker(50);
cambutton.pressColor = paintbutton.highlightColor;
cambutton.labelMinExtent = new Point(36, 18);
cambutton.labelShadowOffset = new Point(-1, -1);
cambutton.labelShadowColor = paintbutton.highlightColor;
cambutton.labelColor = TurtleIconMorph.prototype.labelColor;
cambutton.contrast = this.buttonContrast;
cambutton.hint = "Import a new costume from your webcam";
cambutton.setPosition(new Point(x, y));
cambutton.fixLayout();
cambutton.setCenter(paintbutton.center());
cambutton.setLeft(paintbutton.right() + toolsPadding);
this.addContents(cambutton);
if (!CamSnapshotDialogMorph.prototype.enabled) {
cambutton.disable();
cambutton.hint =
CamSnapshotDialogMorph.prototype.notSupportedMessage;
}
document.addEventListener(
'cameraDisabled',
function () {
cambutton.disable();
cambutton.hint =
CamSnapshotDialogMorph.prototype.notSupportedMessage;
}
);
}
txt = new TextMorph(localize(
"costumes tab help" // look up long string in translator
));
txt.fontSize = 9;
txt.setColor(SpriteMorph.prototype.paletteTextColor);
txt.setPosition(new Point(x, y));
this.addContents(txt);
y = txt.bottom() + padding;
this.sprite.costumes.asArray().forEach(function (costume) {
icon = new CostumeIconMorph(costume);
icon.setPosition(new Point(x, y));
myself.addContents(icon);
y = icon.bottom() + padding;
});
this.costumesVersion = this.sprite.costumes.lastChanged;
this.contents.setPosition(oldPos);
this.adjustScrollBars();
this.changed();
this.updateSelection();
};
WardrobeMorph.prototype.updateSelection = function () {
this.contents.children.forEach(function (morph) {
if (morph.refresh) {morph.refresh(); }
});
this.spriteVersion = this.sprite.version;
};
// Wardrobe stepping
WardrobeMorph.prototype.step = function () {
if (this.costumesVersion !== this.sprite.costumes.lastChanged) {
this.updateList();
}
if (this.spriteVersion !== this.sprite.version) {
this.updateSelection();
}
};
// Wardrobe ops
WardrobeMorph.prototype.removeCostumeAt = function (idx) {
this.sprite.shadowAttribute('costumes');
this.sprite.costumes.remove(idx);
this.updateList();
};
WardrobeMorph.prototype.paintNew = function () {
var cos = new Costume(
newCanvas(null, true),
this.sprite.newCostumeName(localize('Untitled'))
),
ide = this.parentThatIsA(IDE_Morph),
myself = this;
cos.edit(this.world(), ide, true, null, function () {
myself.sprite.shadowAttribute('costumes');
myself.sprite.addCostume(cos);
myself.updateList();
if (ide) {
ide.currentSprite.wearCostume(cos);
}
});
};
WardrobeMorph.prototype.newFromCam = function () {
var camDialog,
ide = this.parentThatIsA(IDE_Morph),
myself = this,
sprite = this.sprite;
camDialog = new CamSnapshotDialogMorph(
ide,
sprite,
nop,
function (costume) {
sprite.addCostume(costume);
sprite.wearCostume(costume);
myself.updateList();
});
camDialog.key = 'camera';
camDialog.popUp(this.world());
};
// Wardrobe drag & drop
WardrobeMorph.prototype.wantsDropOf = function (morph) {
return morph instanceof CostumeIconMorph;
};
WardrobeMorph.prototype.reactToDropOf = function (icon) {
var idx = 0,
costume = icon.object,
top = icon.top();
icon.destroy();
this.contents.children.forEach(function (item) {
if (item instanceof CostumeIconMorph && item.top() < top - 4) {
idx += 1;
}
});
this.sprite.shadowAttribute('costumes');
this.sprite.costumes.add(costume, idx + 1);
this.updateList();
icon.mouseClickLeft(); // select
};
// SoundIconMorph ///////////////////////////////////////////////////////
/*
I am an element in the SpriteEditor's "Sounds" tab.
*/
// SoundIconMorph inherits from ToggleButtonMorph (Widgets)
// ... and copies methods from SpriteIconMorph
SoundIconMorph.prototype = new ToggleButtonMorph();
SoundIconMorph.prototype.constructor = SoundIconMorph;
SoundIconMorph.uber = ToggleButtonMorph.prototype;
// SoundIconMorph settings
SoundIconMorph.prototype.thumbSize = new Point(80, 60);
SoundIconMorph.prototype.labelShadowOffset = null;
SoundIconMorph.prototype.labelShadowColor = null;
SoundIconMorph.prototype.labelColor = new Color(255, 255, 255);
SoundIconMorph.prototype.fontSize = 9;
// SoundIconMorph instance creation:
function SoundIconMorph(aSound) {
this.init(aSound);
}
SoundIconMorph.prototype.init = function (aSound) {
var colors, action, query;
colors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor
];
action = function () {
nop(); // When I am selected (which is never the case for sounds)
};
query = function () {
return false;
};
// additional properties:
this.object = aSound; // mandatory, actually
this.version = this.object.version;
this.thumbnail = null;
// initialize inherited properties:
SoundIconMorph.uber.init.call(
this,
colors, // color overrides, <array>: [normal, highlight, pressed]
null, // target - not needed here
action, // a toggle function
this.object.name, // label string
query, // predicate/selector
null, // environment
null // hint
);
// override defaults and build additional components
this.isDraggable = true;
this.createThumbnail();
this.padding = 2;
this.corner = 8;
this.fixLayout();
this.fps = 1;
};
SoundIconMorph.prototype.createThumbnail = function () {
var label;
if (this.thumbnail) {
this.thumbnail.destroy();
}
this.thumbnail = new Morph();
this.thumbnail.bounds.setExtent(this.thumbSize);
this.add(this.thumbnail);
label = new StringMorph(
this.createInfo(),
'16',
'',
true,
false,
false,
this.labelShadowOffset,
this.labelShadowColor,
new Color(200, 200, 200)
);
this.thumbnail.add(label);
label.setCenter(new Point(40, 15));
this.button = new PushButtonMorph(
this,
'toggleAudioPlaying',
(this.object.previewAudio ? 'Stop' : 'Play')
);
this.button.hint = 'Play sound';
this.button.fixLayout();
this.thumbnail.add(this.button);
this.button.setCenter(new Point(40, 40));
};
SoundIconMorph.prototype.createInfo = function () {
var dur = Math.round(this.object.audio.duration || 0),
mod = dur % 60;
return Math.floor(dur / 60).toString()
+ ":"
+ (mod < 10 ? "0" : "")
+ mod.toString();
};
SoundIconMorph.prototype.toggleAudioPlaying = function () {
var myself = this;
if (!this.object.previewAudio) {
//Audio is not playing
this.button.labelString = 'Stop';
this.button.hint = 'Stop sound';
this.object.previewAudio = this.object.play();
this.object.previewAudio.addEventListener('ended', function () {
myself.audioHasEnded();
}, false);
} else {
//Audio is currently playing
this.button.labelString = 'Play';
this.button.hint = 'Play sound';
this.object.previewAudio.pause();
this.object.previewAudio.terminated = true;
this.object.previewAudio = null;
}
this.button.createLabel();
};
SoundIconMorph.prototype.audioHasEnded = function () {
this.button.trigger();
this.button.mouseLeave();
};
SoundIconMorph.prototype.createLabel
= SpriteIconMorph.prototype.createLabel;
// SoundIconMorph stepping
/*
SoundIconMorph.prototype.step
= SpriteIconMorph.prototype.step;
*/
// SoundIconMorph layout
SoundIconMorph.prototype.fixLayout
= SpriteIconMorph.prototype.fixLayout;
// SoundIconMorph menu
SoundIconMorph.prototype.userMenu = function () {
var menu = new MenuMorph(this);
if (!(this.object instanceof Sound)) { return null; }
menu.addItem('rename', 'renameSound');
menu.addItem('delete', 'removeSound');
menu.addLine();
menu.addItem('export', 'exportSound');
return menu;
};
SoundIconMorph.prototype.renameSound = function () {
var sound = this.object,
ide = this.parentThatIsA(IDE_Morph),
myself = this;
this.disinherit();
(new DialogBoxMorph(
null,
function (answer) {
if (answer && (answer !== sound.name)) {
sound.name = answer;
sound.version = Date.now();
myself.createLabel(); // can be omitted once I'm stepping
myself.fixLayout(); // can be omitted once I'm stepping
ide.hasChangedMedia = true;
}
}
)).prompt(
'rename sound',
sound.name,
this.world()
);
};
SoundIconMorph.prototype.removeSound = function () {
var jukebox = this.parentThatIsA(JukeboxMorph),
idx = this.parent.children.indexOf(this) - 1;
jukebox.removeSound(idx);
};
SoundIconMorph.prototype.exportSound = function () {
var ide = this.parentThatIsA(IDE_Morph);
ide.saveAudioAs(this.object.audio, this.object.name);
};
SoundIconMorph.prototype.render
= SpriteIconMorph.prototype.render;
SoundIconMorph.prototype.createLabel
= SpriteIconMorph.prototype.createLabel;
// SoundIconMorph inheritance
SoundIconMorph.prototype.disinherit = function () {
var jukebox = this.parentThatIsA(JukeboxMorph),
idx = this.parent.children.indexOf(this);
if (jukebox.sprite.inheritsAttribute('sounds')) {
jukebox.sprite.shadowAttribute('sounds');
this.object = jukebox.sprite.sounds.at(idx - 1);
}
};
// SoundIconMorph drag & drop
SoundIconMorph.prototype.prepareToBeGrabbed = function () {
this.disinherit();
this.userState = 'pressed';
this.state = true;
this.rerender();
this.removeSound();
};
// JukeboxMorph /////////////////////////////////////////////////////
/*
I am JukeboxMorph, like WardrobeMorph, but for sounds
*/
// JukeboxMorph instance creation
JukeboxMorph.prototype = new ScrollFrameMorph();
JukeboxMorph.prototype.constructor = JukeboxMorph;
JukeboxMorph.uber = ScrollFrameMorph.prototype;
function JukeboxMorph(aSprite, sliderColor) {
this.init(aSprite, sliderColor);
}
JukeboxMorph.prototype.init = function (aSprite, sliderColor) {
// additional properties
this.sprite = aSprite || new SpriteMorph();
this.soundsVersion = null;
this.spriteVersion = null;
// initialize inherited properties
JukeboxMorph.uber.init.call(this, null, null, sliderColor);
// configure inherited properties
this.acceptsDrops = false;
this.fps = 2;
this.updateList();
};
// Jukebox updating
JukeboxMorph.prototype.updateList = function () {
var myself = this,
x = this.left() + 5,
y = this.top() + 5,
padding = 4,
icon,
txt,
ide = this.sprite.parentThatIsA(IDE_Morph),
recordButton;
this.changed();
this.contents.destroy();
this.contents = new FrameMorph(this);
this.contents.acceptsDrops = false;
this.contents.reactToDropOf = function (icon) {
myself.reactToDropOf(icon);
};
this.addBack(this.contents);
txt = new TextMorph(localize(
'import a sound from your computer\nby dragging it into here'
));
txt.fontSize = 9;
txt.setColor(SpriteMorph.prototype.paletteTextColor);
txt.setPosition(new Point(x, y));
this.addContents(txt);
recordButton = new PushButtonMorph(
ide,
'recordNewSound',
new SymbolMorph('circleSolid', 15)
);
recordButton.padding = 0;
recordButton.corner = 12;
recordButton.color = IDE_Morph.prototype.groupColor;
recordButton.highlightColor = IDE_Morph.prototype.frameColor.darker(50);
recordButton.pressColor = recordButton.highlightColor;
recordButton.labelMinExtent = new Point(36, 18);
recordButton.labelShadowOffset = new Point(-1, -1);
recordButton.labelShadowColor = recordButton.highlightColor;
recordButton.labelColor = TurtleIconMorph.prototype.labelColor;
recordButton.contrast = this.buttonContrast;
recordButton.hint = 'Record a new sound';
recordButton.fixLayout();
recordButton.label.setColor(new Color(255, 20, 20));
recordButton.setPosition(txt.bottomLeft().add(new Point(0, padding * 2)));
this.addContents(recordButton);
y = recordButton.bottom() + padding;
this.sprite.sounds.asArray().forEach(function (sound) {
icon = new SoundIconMorph(sound);
icon.setPosition(new Point(x, y));
myself.addContents(icon);
y = icon.bottom() + padding;
});
this.soundsVersion = this.sprite.sounds.lastChanged;
this.changed();
this.updateSelection();
};
JukeboxMorph.prototype.updateSelection = function () {
this.contents.children.forEach(function (morph) {
if (morph.refresh) {morph.refresh(); }
});
this.spriteVersion = this.sprite.version;
};
// Jukebox stepping
JukeboxMorph.prototype.step = function () {
if (this.soundsVersion !== this.sprite.sounds.lastChanged) {
this.updateList();
}
if (this.spriteVersion !== this.sprite.version) {
this.updateSelection();
}
};
// Jukebox ops
JukeboxMorph.prototype.removeSound = function (idx) {
this.sprite.sounds.remove(idx);
this.updateList();
};
// Jukebox drag & drop
JukeboxMorph.prototype.wantsDropOf = function (morph) {
return morph instanceof SoundIconMorph;
};
JukeboxMorph.prototype.reactToDropOf = function (icon) {
var idx = 0,
costume = icon.object,
top = icon.top();
icon.destroy();
this.contents.children.forEach(function (item) {
if (item instanceof SoundIconMorph && item.top() < top - 4) {
idx += 1;
}
});
this.sprite.shadowAttribute('sounds');
this.sprite.sounds.add(costume, idx + 1);
this.updateList();
};
// StageHandleMorph ////////////////////////////////////////////////////////
// I am a horizontal resizing handle for a StageMorph
// StageHandleMorph inherits from Morph:
StageHandleMorph.prototype = new Morph();
StageHandleMorph.prototype.constructor = StageHandleMorph;
StageHandleMorph.uber = Morph.prototype;
// StageHandleMorph instance creation:
function StageHandleMorph(target) {
this.init(target);
}
StageHandleMorph.prototype.init = function (target) {
this.target = target || null;
this.userState = 'normal'; // or 'highlight'
HandleMorph.uber.init.call(this);
this.color = MorphicPreferences.isFlat ?
IDE_Morph.prototype.backgroundColor : new Color(190, 190, 190);
this.isDraggable = false;
this.setExtent(new Point(12, 50));
};
// StageHandleMorph drawing:
StageHandleMorph.prototype.render = function (ctx) {
if (this.userState === 'highlight') {
this.renderOn(
ctx,
MorphicPreferences.isFlat ?
new Color(245, 245, 255) : new Color(100, 100, 255),
this.color
);
} else { // assume 'normal'
this.renderOn(ctx, this.color);
}
};
StageHandleMorph.prototype.renderOn = function (
ctx,
color,
shadowColor
) {
var l = this.height() / 8,
w = this.width() / 6,
r = w / 2,
x,
y,
i;
ctx.lineWidth = w;
ctx.lineCap = 'round';
y = this.height() / 2;
ctx.strokeStyle = color.toString();
x = this.width() / 12;
for (i = 0; i < 3; i += 1) {
if (i > 0) {
ctx.beginPath();
ctx.moveTo(x, y - (l - r));
ctx.lineTo(x, y + (l - r));
ctx.stroke();
}
x += (w * 2);
l *= 2;
}
if (shadowColor) {
ctx.strokeStyle = shadowColor.toString();
x = this.width() / 12 + w;
l = this.height() / 8;
for (i = 0; i < 3; i += 1) {
if (i > 0) {
ctx.beginPath();
ctx.moveTo(x, y - (l - r));
ctx.lineTo(x, y + (l - r));
ctx.stroke();
}
x += (w * 2);
l *= 2;
}
}
};
// StageHandleMorph layout:
StageHandleMorph.prototype.fixLayout = function () {
if (!this.target) {return; }
var ide = this.target.parentThatIsA(IDE_Morph);
this.setTop(this.target.top() + 10);
this.setRight(this.target.left());
if (ide) {ide.add(this); } // come to front
};
// StageHandleMorph stepping:
StageHandleMorph.prototype.step = null;
StageHandleMorph.prototype.mouseDownLeft = function (pos) {
var world = this.world(),
offset = this.right() - pos.x,
myself = this,
ide = this.target.parentThatIsA(IDE_Morph);
if (!this.target) {
return null;
}
ide.isSmallStage = true;
ide.controlBar.stageSizeButton.refresh();
this.step = function () {
var newPos, newWidth;
if (world.hand.mouseButton) {
newPos = world.hand.bounds.origin.x + offset;
newWidth = myself.target.right() - newPos;
ide.stageRatio = newWidth / myself.target.dimensions.x;
ide.setExtent(world.extent());
} else {
this.step = null;
ide.isSmallStage = (ide.stageRatio !== 1);
ide.controlBar.stageSizeButton.refresh();
}
};
};
// StageHandleMorph events:
StageHandleMorph.prototype.mouseEnter = function () {
this.userState = 'highlight';
this.rerender();
};
StageHandleMorph.prototype.mouseLeave = function () {
this.userState = 'normal';
this.rerender();
};
StageHandleMorph.prototype.mouseDoubleClick = function () {
this.target.parentThatIsA(IDE_Morph).toggleStageSize(true, 1);
};
// PaletteHandleMorph ////////////////////////////////////////////////////////
// I am a horizontal resizing handle for a blocks palette
// I pseudo-inherit many things from StageHandleMorph
// PaletteHandleMorph inherits from Morph:
PaletteHandleMorph.prototype = new Morph();
PaletteHandleMorph.prototype.constructor = PaletteHandleMorph;
PaletteHandleMorph.uber = Morph.prototype;
// PaletteHandleMorph instance creation:
function PaletteHandleMorph(target) {
this.init(target);
}
PaletteHandleMorph.prototype.init = function (target) {
this.target = target || null;
this.userState = 'normal';
HandleMorph.uber.init.call(this);
this.color = MorphicPreferences.isFlat ?
IDE_Morph.prototype.backgroundColor : new Color(190, 190, 190);
this.isDraggable = false;
this.setExtent(new Point(12, 50));
};
// PaletteHandleMorph drawing:
PaletteHandleMorph.prototype.render =
StageHandleMorph.prototype.render;
PaletteHandleMorph.prototype.renderOn =
StageHandleMorph.prototype.renderOn;
// PaletteHandleMorph layout:
PaletteHandleMorph.prototype.fixLayout = function () {
if (!this.target) {return; }
var ide = this.target.parentThatIsA(IDE_Morph);
this.setTop(this.target.top() + 10);
this.setRight(this.target.right());
if (ide) {ide.add(this); } // come to front
};
// PaletteHandleMorph stepping:
PaletteHandleMorph.prototype.step = null;
PaletteHandleMorph.prototype.mouseDownLeft = function (pos) {
var world = this.world(),
offset = this.right() - pos.x,
ide = this.target.parentThatIsA(IDE_Morph);
if (!this.target) {
return null;
}
this.step = function () {
var newPos;
if (world.hand.mouseButton) {
newPos = world.hand.bounds.origin.x + offset;
ide.paletteWidth = Math.min(
Math.max(200, newPos),
ide.stageHandle.left() - ide.spriteBar.tabBar.width()
);
ide.setExtent(world.extent());
} else {
this.step = null;
}
};
};
// PaletteHandleMorph events:
PaletteHandleMorph.prototype.mouseEnter
= StageHandleMorph.prototype.mouseEnter;
PaletteHandleMorph.prototype.mouseLeave
= StageHandleMorph.prototype.mouseLeave;
PaletteHandleMorph.prototype.mouseDoubleClick = function () {
this.target.parentThatIsA(IDE_Morph).setPaletteWidth(200);
};
// CamSnapshotDialogMorph ////////////////////////////////////////////////////
/*
I am a dialog morph that lets users take a snapshot using their webcam
and use it as a costume for their sprites or a background for the Stage.
NOTE: Currently disabled because of issues with experimental technology
in Safari.
*/
// CamSnapshotDialogMorph inherits from DialogBoxMorph:
CamSnapshotDialogMorph.prototype = new DialogBoxMorph();
CamSnapshotDialogMorph.prototype.constructor = CamSnapshotDialogMorph;
CamSnapshotDialogMorph.uber = DialogBoxMorph.prototype;
// CamSnapshotDialogMorph settings
CamSnapshotDialogMorph.prototype.enableCamera = true; // off while experimental
CamSnapshotDialogMorph.prototype.enabled = true;
CamSnapshotDialogMorph.prototype.notSupportedMessage =
'Please make sure your web browser is up to date\n' +
'and your camera is properly configured. \n\n' +
'Some browsers also require you to access Snap!\n' +
'through HTTPS to use the camera.\n\n' +
'Plase replace the "http://" part of the address\n' +
'in your browser by "https://" and try again.';
// CamSnapshotDialogMorph instance creation
function CamSnapshotDialogMorph(ide, sprite, onCancel, onAccept) {
this.init(ide, sprite, onCancel, onAccept);
}
CamSnapshotDialogMorph.prototype.init = function (
ide,
sprite,
onCancel,
onAccept
) {
this.ide = ide;
this.sprite = sprite;
this.padding = 10;
this.oncancel = onCancel;
this.accept = onAccept;
this.videoElement = null; // an HTML5 video element
this.videoView = new Morph(); // a morph where we'll copy the video contents
this.videoView.isCachingImage = true;
CamSnapshotDialogMorph.uber.init.call(this);
this.labelString = 'Camera';
this.createLabel();
this.buildContents();
};
CamSnapshotDialogMorph.prototype.buildContents = function () {
var myself = this,
stage = this.sprite.parentThatIsA(StageMorph);
function noCameraSupport() {
myself.disable();
myself.ide.inform(
'Camera not supported',
CamSnapshotDialogMorph.prototype.notSupportedMessage
);
if (myself.videoElement) {
myself.videoElement.remove();
}
myself.cancel();
}
this.videoElement = document.createElement('video');
this.videoElement.hidden = true;
this.videoElement.width = stage.dimensions.x;
this.videoElement.height = stage.dimensions.y;
document.body.appendChild(this.videoElement);
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
myself.videoElement.srcObject = stream;
myself.videoElement.play().catch(noCameraSupport);
myself.videoElement.stream = stream;
})
.catch(noCameraSupport);
}
this.videoView.setExtent(stage.dimensions);
this.videoView.cachedImage = newCanvas(
stage.dimensions,
true, // retina, maybe overkill here
this.videoView.cachedImage
);
this.videoView.drawOn = function (ctx, rect) {
var videoWidth = myself.videoElement.videoWidth,
videoHeight = myself.videoElement.videoHeight,
w = stage.dimensions.x,
h = stage.dimensions.y,
clippingWidth, clippingHeight;
if (!videoWidth) { return; }
ctx.save();
// Flip the image so it looks like a mirror
ctx.translate(w, 0);
ctx.scale(-1, 1);
if (videoWidth / w > videoHeight / h) {
// preserve height, crop width
clippingWidth = w * (videoHeight / h);
clippingHeight = videoHeight;
} else {
// preserve width, crop height
clippingWidth = videoWidth;
clippingHeight = h * (videoWidth / w);
}
ctx.drawImage(
myself.videoElement,
0,
0,
clippingWidth,
clippingHeight,
this.left() * -1,
this.top(),
w,
h
);
ctx.restore();
};
this.videoView.step = function () {
this.changed();
};
this.addBody(new AlignmentMorph('column', this.padding / 2));
this.body.add(this.videoView);
this.body.fixLayout();
this.addButton('ok', 'Save');
this.addButton('cancel', 'Cancel');
this.fixLayout();
this.rerender();
};
CamSnapshotDialogMorph.prototype.ok = function () {
this.accept(
new Costume(
this.videoView.fullImage(),
this.sprite.newCostumeName('camera')
).flipped()
);
};
CamSnapshotDialogMorph.prototype.disable = function () {
CamSnapshotDialogMorph.prototype.enabled = false;
document.dispatchEvent(new Event('cameraDisabled'));
};
CamSnapshotDialogMorph.prototype.destroy = function () {
this.oncancel.call(this);
this.close();
};
CamSnapshotDialogMorph.prototype.close = function () {
if (this.videoElement && this.videoElement.stream) {
this.videoElement.stream.getTracks()[0].stop();
this.videoElement.remove();
}
CamSnapshotDialogMorph.uber.destroy.call(this);
};
// SoundRecorderDialogMorph ////////////////////////////////////////////////////
/*
I am a dialog morph that lets users record sound snippets for their
sprites or Stage.
*/
// SoundRecorderDialogMorph inherits from DialogBoxMorph:
SoundRecorderDialogMorph.prototype = new DialogBoxMorph();
SoundRecorderDialogMorph.prototype.constructor = SoundRecorderDialogMorph;
SoundRecorderDialogMorph.uber = DialogBoxMorph.prototype;
// SoundRecorderDialogMorph instance creation
function SoundRecorderDialogMorph(onAccept) {
this.init(onAccept);
}
SoundRecorderDialogMorph.prototype.init = function (onAccept) {
var myself = this;
this.padding = 10;
this.accept = onAccept;
this.mediaRecorder = null; // an HTML5 MediaRecorder object
this.audioElement = document.createElement('audio');
this.audioElement.hidden = true;
this.audioElement.onended = function (event) {
myself.stop();
};
document.body.appendChild(this.audioElement);
this.recordButton = null;
this.stopButton = null;
this.playButton = null;
this.progressBar = new BoxMorph();
SoundRecorderDialogMorph.uber.init.call(this);
this.labelString = 'Sound Recorder';
this.createLabel();
this.buildContents();
};
SoundRecorderDialogMorph.prototype.buildContents = function () {
var myself = this,
audioChunks = [];
this.recordButton = new PushButtonMorph(
this,
'record',
new SymbolMorph('circleSolid', 10)
);
this.stopButton = new PushButtonMorph(
this,
'stop',
new SymbolMorph('rectangleSolid', 10)
);
this.playButton = new PushButtonMorph(
this,
'play',
new SymbolMorph('pointRight', 10)
);
this.buildProgressBar();
this.addBody(new AlignmentMorph('row', this.padding));
this.body.add(this.recordButton);
this.body.add(this.stopButton);
this.body.add(this.playButton);
this.body.add(this.progressBar);
this.body.fixLayout();
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(
{
audio: {
channelCount: 1 // force mono, currently only works on FF
}
}
).then(function (stream) {
myself.mediaRecorder = new MediaRecorder(stream);
myself.mediaRecorder.ondataavailable = function (event) {
audioChunks.push(event.data);
};
myself.mediaRecorder.onstop = function (event) {
var buffer = new Blob(audioChunks),
reader = new window.FileReader();
reader.readAsDataURL(buffer);
reader.onloadend = function() {
var base64 = reader.result;
base64 = 'data:audio/ogg;base64,' +
base64.split(',')[1];
myself.audioElement.src = base64;
myself.audioElement.load();
audioChunks = [];
};
};
});
}
this.addButton('ok', 'Save');
this.addButton('cancel', 'Cancel');
this.fixLayout();
this.rerender();
};
SoundRecorderDialogMorph.prototype.buildProgressBar = function () {
var line = new Morph(),
myself = this;
this.progressBar.setExtent(new Point(150, 20));
this.progressBar.setColor(new Color(200, 200, 200));
this.progressBar.setBorderWidth(1);
this.progressBar.setBorderColor(new Color(150, 150, 150));
line.setExtent(new Point(130, 2));
line.setColor(new Color(50, 50, 50));
line.setCenter(this.progressBar.center());
this.progressBar.add(line);
this.progressBar.indicator = new Morph();
this.progressBar.indicator.setExtent(new Point(5, 15));
this.progressBar.indicator.setColor(new Color(50, 200, 50));
this.progressBar.indicator.setCenter(line.leftCenter());
this.progressBar.add(this.progressBar.indicator);
this.progressBar.setPercentage = function (percentage) {
this.indicator.setLeft(
line.left() +
(line.width() / 100 * percentage) -
this.indicator.width() / 2
);
};
this.progressBar.step = function () {
if (myself.audioElement.duration) {
this.setPercentage(
myself.audioElement.currentTime /
myself.audioElement.duration * 100);
} else {
this.setPercentage(0);
}
};
};
SoundRecorderDialogMorph.prototype.record = function () {
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
this.stop();
return;
}
this.mediaRecorder.start();
this.recordButton.label.setColor(new Color(255, 0, 0));
this.playButton.label.setColor(new Color(0, 0, 0));
};
SoundRecorderDialogMorph.prototype.stop = function () {
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
this.mediaRecorder.stop();
}
this.audioElement.pause();
this.audioElement.currentTime = 0;
this.recordButton.label.setColor(new Color(0, 0, 0));
this.playButton.label.setColor(new Color(0, 0, 0));
};
SoundRecorderDialogMorph.prototype.play = function () {
this.stop();
this.audioElement.oncanplaythrough = function () {
this.play();
this.oncanplaythrough = nop;
};
this.playButton.label.setColor(new Color(0, 255, 0));
};
SoundRecorderDialogMorph.prototype.ok = function () {
var myself = this;
this.stop();
this.audioElement.oncanplaythrough = function () {
if (this.duration && this.duration !== Infinity) {
myself.accept(this);
this.oncanplaythrough = nop;
myself.destroy();
} else {
// For some reason, we need to play the sound
// at least once to get its duration.
myself.buttons.children.forEach(function (button) {
button.disable();
});
this.play();
}
};
};
SoundRecorderDialogMorph.prototype.destroy = function () {
this.stop();
this.audioElement.remove();
if (this.mediaRecorder) {
this.mediaRecorder.stream.getTracks()[0].stop();
}
SoundRecorderDialogMorph.uber.destroy.call(this);
};
| src/gui.js | /*
gui.js
a programming environment
based on morphic.js, blocks.js, threads.js and objects.js
inspired by Scratch
written by Jens Mönig
[email protected]
Copyright (C) 2020 by Jens Mönig
This file is part of Snap!.
Snap! is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
prerequisites:
--------------
needs blocks.js, threads.js, objects.js, cloud.jus and morphic.js
toc
---
the following list shows the order in which all constructors are
defined. Use this list to locate code in this document:
IDE_Morph
ProjectDialogMorph
SpriteIconMorph
TurtleIconMorph
CostumeIconMorph
WardrobeMorph
StageHandleMorph
PaletteHandleMorph
CamSnapshotDialogMorph
SoundRecorderDialogMorph
credits
-------
Nathan Dinsmore contributed saving and loading of projects,
ypr-Snap! project conversion and countless bugfixes
Ian Reynolds contributed handling and visualization of sounds
Michael Ball contributed the LibraryImportDialogMorph and countless
utilities to load libraries from relative urls
Bernat Romagosa contributed more things than I can mention,
including interfacing to the camera and microphone
*/
/*global modules, Morph, SpriteMorph, SyntaxElementMorph, Color, Cloud, Audio,
ListWatcherMorph, TextMorph, newCanvas, useBlurredShadows, VariableFrame, Sound,
StringMorph, Point, MenuMorph, morphicVersion, DialogBoxMorph, normalizeCanvas,
ToggleButtonMorph, contains, ScrollFrameMorph, StageMorph, PushButtonMorph, sb,
InputFieldMorph, FrameMorph, Process, nop, SnapSerializer, ListMorph, detect,
AlignmentMorph, TabMorph, Costume, MorphicPreferences,BlockMorph, ToggleMorph,
InputSlotDialogMorph, ScriptsMorph, isNil, SymbolMorph, fontHeight, localize,
BlockExportDialogMorph, BlockImportDialogMorph, SnapTranslator, List, ArgMorph,
Uint8Array, HandleMorph, SVG_Costume, TableDialogMorph, CommentMorph, saveAs,
CommandBlockMorph, BooleanSlotMorph, RingReporterSlotMorph, ScriptFocusMorph,
BlockLabelPlaceHolderMorph, SpeechBubbleMorph, XML_Element, WatcherMorph,
BlockRemovalDialogMorph,TableMorph, isSnapObject, isRetinaEnabled, SliderMorph,
disableRetinaSupport, enableRetinaSupport, isRetinaSupported, MediaRecorder,
Animation, BoxMorph, BlockEditorMorph, BlockDialogMorph, Note*/
// Global stuff ////////////////////////////////////////////////////////
modules.gui = '2020-April-30';
// Declarations
var IDE_Morph;
var ProjectDialogMorph;
var LibraryImportDialogMorph;
var SpriteIconMorph;
var CostumeIconMorph;
var TurtleIconMorph;
var WardrobeMorph;
var SoundIconMorph;
var JukeboxMorph;
var StageHandleMorph;
var PaletteHandleMorph;
var CamSnapshotDialogMorph;
var SoundRecorderDialogMorph;
// IDE_Morph ///////////////////////////////////////////////////////////
// I am SNAP's top-level frame, the Editor window
// IDE_Morph inherits from Morph:
IDE_Morph.prototype = new Morph();
IDE_Morph.prototype.constructor = IDE_Morph;
IDE_Morph.uber = Morph.prototype;
// IDE_Morph preferences settings and skins
IDE_Morph.prototype.setDefaultDesign = function () {
MorphicPreferences.isFlat = false;
SpriteMorph.prototype.paletteColor = new Color(55, 55, 55);
SpriteMorph.prototype.paletteTextColor = new Color(230, 230, 230);
StageMorph.prototype.paletteTextColor
= SpriteMorph.prototype.paletteTextColor;
StageMorph.prototype.paletteColor = SpriteMorph.prototype.paletteColor;
SpriteMorph.prototype.sliderColor
= SpriteMorph.prototype.paletteColor.lighter(30);
IDE_Morph.prototype.buttonContrast = 30;
IDE_Morph.prototype.backgroundColor = new Color(40, 40, 40);
IDE_Morph.prototype.frameColor = SpriteMorph.prototype.paletteColor;
IDE_Morph.prototype.groupColor
= SpriteMorph.prototype.paletteColor.lighter(8);
IDE_Morph.prototype.sliderColor = SpriteMorph.prototype.sliderColor;
IDE_Morph.prototype.buttonLabelColor = new Color(255, 255, 255);
IDE_Morph.prototype.tabColors = [
IDE_Morph.prototype.groupColor.darker(40),
IDE_Morph.prototype.groupColor.darker(60),
IDE_Morph.prototype.groupColor
];
IDE_Morph.prototype.rotationStyleColors = IDE_Morph.prototype.tabColors;
IDE_Morph.prototype.appModeColor = new Color();
IDE_Morph.prototype.scriptsPaneTexture = this.scriptsTexture();
IDE_Morph.prototype.padding = 5;
SpriteIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
CostumeIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
SoundIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
TurtleIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
SyntaxElementMorph.prototype.contrast = 65;
ScriptsMorph.prototype.feedbackColor = new Color(255, 255, 255);
};
IDE_Morph.prototype.setFlatDesign = function () {
MorphicPreferences.isFlat = true;
SpriteMorph.prototype.paletteColor = new Color(255, 255, 255);
SpriteMorph.prototype.paletteTextColor = new Color(70, 70, 70);
StageMorph.prototype.paletteTextColor
= SpriteMorph.prototype.paletteTextColor;
StageMorph.prototype.paletteColor = SpriteMorph.prototype.paletteColor;
SpriteMorph.prototype.sliderColor = SpriteMorph.prototype.paletteColor;
IDE_Morph.prototype.buttonContrast = 30;
IDE_Morph.prototype.backgroundColor = new Color(220, 220, 230);
IDE_Morph.prototype.frameColor = new Color(240, 240, 245);
IDE_Morph.prototype.groupColor = new Color(255, 255, 255);
IDE_Morph.prototype.sliderColor = SpriteMorph.prototype.sliderColor;
IDE_Morph.prototype.buttonLabelColor = new Color(70, 70, 70);
IDE_Morph.prototype.tabColors = [
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor.lighter(50),
IDE_Morph.prototype.groupColor
];
IDE_Morph.prototype.rotationStyleColors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.groupColor.darker(10),
IDE_Morph.prototype.groupColor.darker(30)
];
IDE_Morph.prototype.appModeColor = IDE_Morph.prototype.frameColor;
IDE_Morph.prototype.scriptsPaneTexture = null;
IDE_Morph.prototype.padding = 1;
SpriteIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
CostumeIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
SoundIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
TurtleIconMorph.prototype.labelColor
= IDE_Morph.prototype.buttonLabelColor;
SyntaxElementMorph.prototype.contrast = 25;
ScriptsMorph.prototype.feedbackColor = new Color(153, 255, 213);
};
IDE_Morph.prototype.scriptsTexture = function () {
var pic = newCanvas(new Point(100, 100)), // bigger scales faster
ctx = pic.getContext('2d'),
i;
for (i = 0; i < 100; i += 4) {
ctx.fillStyle = this.frameColor.toString();
ctx.fillRect(i, 0, 1, 100);
ctx.fillStyle = this.groupColor.lighter(6).toString();
ctx.fillRect(i + 1, 0, 1, 100);
ctx.fillRect(i + 3, 0, 1, 100);
ctx.fillStyle = this.groupColor.toString();
ctx.fillRect(i + 2, 0, 1, 100);
}
return pic;
};
IDE_Morph.prototype.setDefaultDesign();
// IDE_Morph instance creation:
function IDE_Morph(isAutoFill) {
this.init(isAutoFill);
}
IDE_Morph.prototype.init = function (isAutoFill) {
// global font setting
MorphicPreferences.globalFontFamily = 'Helvetica, Arial';
// restore saved user preferences
this.userLanguage = null; // user language preference for startup
this.projectsInURLs = false;
this.applySavedSettings();
// additional properties:
this.cloud = new Cloud();
this.cloudMsg = null;
this.source = null;
this.serializer = new SnapSerializer();
this.globalVariables = new VariableFrame();
this.currentSprite = new SpriteMorph(this.globalVariables);
this.sprites = new List([this.currentSprite]);
this.currentCategory = 'motion';
this.currentTab = 'scripts';
this.projectName = '';
this.projectNotes = '';
// logoURL is disabled because the image data is hard-copied
// to avoid tainting the world canvas
// this.logoURL = this.resourceURL('src', 'snap_logo_sm.png');
this.logo = null;
this.controlBar = null;
this.categories = null;
this.palette = null;
this.paletteHandle = null;
this.spriteBar = null;
this.spriteEditor = null;
this.stage = null;
this.stageHandle = null;
this.corralBar = null;
this.corral = null;
this.embedPlayButton = null;
this.embedOverlay = null;
this.isEmbedMode = false;
this.isAutoFill = isAutoFill === undefined ? true : isAutoFill;
this.isAppMode = false;
this.isSmallStage = false;
this.filePicker = null;
this.hasChangedMedia = false;
this.isAnimating = true;
this.paletteWidth = 200; // initially same as logo width
this.stageRatio = 1; // for IDE animations, e.g. when zooming
this.wasSingleStepping = false; // for toggling to and from app mode
this.loadNewProject = false; // flag when starting up translated
this.shield = null;
this.savingPreferences = true; // for bh's infamous "Eisenbergification"
// initialize inherited properties:
IDE_Morph.uber.init.call(this);
// override inherited properites:
this.color = this.backgroundColor;
};
IDE_Morph.prototype.openIn = function (world) {
var hash, myself = this, urlLanguage = null;
function initUser(username) {
sessionStorage.username = username;
if (username) {
myself.source = 'cloud';
if (!myself.cloud.verified) {
new DialogBoxMorph().inform(
'Unverified account',
'Your account is still unverified.\n' +
'Please use the verification link that\n' +
'was sent to your email address when you\n' +
'signed up.\n\n' +
'If you cannot find that email, please\n' +
'check your spam folder. If you still\n' +
'cannot find it, please use the "Resend\n' +
'Verification Email..." option in the cloud\n' +
'menu.',
world,
myself.cloudIcon(null, new Color(0, 180, 0))
);
}
}
}
if (location.protocol !== 'file:') {
if (!sessionStorage.username) {
// check whether login should persist across browser sessions
this.cloud.initSession(initUser);
} else {
// login only persistent during a single browser session
this.cloud.checkCredentials(initUser);
}
}
this.buildPanes();
world.add(this);
world.userMenu = this.userMenu;
// override SnapCloud's user message with Morphic
this.cloud.message = (string) => {
var m = new MenuMorph(null, string),
intervalHandle;
m.popUpCenteredInWorld(world);
intervalHandle = setInterval(() => {
m.destroy();
clearInterval(intervalHandle);
}, 2000);
};
// prevent non-DialogBoxMorphs from being dropped
// onto the World in user-mode
world.reactToDropOf = (morph) => {
if (!(morph instanceof DialogBoxMorph ||
(morph instanceof MenuMorph))) {
if (world.hand.grabOrigin) {
morph.slideBackTo(world.hand.grabOrigin);
} else {
world.hand.grab(morph);
}
}
};
this.reactToWorldResize(world.bounds);
function getURL(url) {
try {
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send();
if (request.status === 200) {
return request.responseText;
}
throw new Error('unable to retrieve ' + url);
} catch (err) {
myself.showMessage('unable to retrieve project');
return '';
}
}
function applyFlags(dict) {
if (dict.embedMode) {
myself.setEmbedMode();
}
if (dict.editMode) {
myself.toggleAppMode(false);
} else {
myself.toggleAppMode(true);
}
if (!dict.noRun) {
myself.runScripts();
}
if (dict.hideControls) {
myself.controlBar.hide();
window.onbeforeunload = nop;
}
if (dict.noExitWarning) {
window.onbeforeunload = nop;
}
if (dict.lang) {
myself.setLanguage(dict.lang, null, true); // don't persist
}
// only force my world to get focus if I'm not in embed mode
// to prevent the iFrame from involuntarily scrolling into view
if (!myself.isEmbedMode) {
world.worldCanvas.focus();
}
}
// dynamic notifications from non-source text files
// has some issues, commented out for now
/*
this.cloudMsg = getURL('https://snap.berkeley.edu/cloudmsg.txt');
motd = getURL('https://snap.berkeley.edu/motd.txt');
if (motd) {
this.inform('Snap!', motd);
}
*/
function interpretUrlAnchors() {
var dict, idx;
if (location.hash.substr(0, 6) === '#open:') {
hash = location.hash.substr(6);
if (hash.charAt(0) === '%'
|| hash.search(/\%(?:[0-9a-f]{2})/i) > -1) {
hash = decodeURIComponent(hash);
}
if (contains(
['project', 'blocks', 'sprites', 'snapdata'].map(each =>
hash.substr(0, 8).indexOf(each)
),
1
)) {
this.droppedText(hash);
} else {
idx = hash.indexOf("&");
if (idx > 0) {
dict = myself.cloud.parseDict(hash.substr(idx));
dict.editMode = true;
hash = hash.slice(0, idx);
applyFlags(dict);
}
this.droppedText(getURL(hash));
}
} else if (location.hash.substr(0, 5) === '#run:') {
hash = location.hash.substr(5);
idx = hash.indexOf("&");
if (idx > 0) {
hash = hash.slice(0, idx);
}
if (hash.charAt(0) === '%'
|| hash.search(/\%(?:[0-9a-f]{2})/i) > -1) {
hash = decodeURIComponent(hash);
}
if (hash.substr(0, 8) === '<project>') {
this.rawOpenProjectString(hash);
} else {
this.rawOpenProjectString(getURL(hash));
}
applyFlags(myself.cloud.parseDict(location.hash.substr(5)));
} else if (location.hash.substr(0, 9) === '#present:') {
this.shield = new Morph();
this.shield.color = this.color;
this.shield.setExtent(this.parent.extent());
this.parent.add(this.shield);
myself.showMessage('Fetching project\nfrom the cloud...');
// make sure to lowercase the username
dict = myself.cloud.parseDict(location.hash.substr(9));
dict.Username = dict.Username.toLowerCase();
myself.cloud.getPublicProject(
dict.ProjectName,
dict.Username,
projectData => {
var msg;
myself.nextSteps([
() => msg = myself.showMessage('Opening project...'),
() => {
if (projectData.indexOf('<snapdata') === 0) {
myself.rawOpenCloudDataString(projectData);
} else if (
projectData.indexOf('<project') === 0
) {
myself.rawOpenProjectString(projectData);
}
myself.hasChangedMedia = true;
},
() => {
myself.shield.destroy();
myself.shield = null;
msg.destroy();
applyFlags(dict);
}
]);
},
this.cloudError()
);
} else if (location.hash.substr(0, 7) === '#cloud:') {
this.shield = new Morph();
this.shield.alpha = 0;
this.shield.setExtent(this.parent.extent());
this.parent.add(this.shield);
myself.showMessage('Fetching project\nfrom the cloud...');
// make sure to lowercase the username
dict = myself.cloud.parseDict(location.hash.substr(7));
myself.cloud.getPublicProject(
dict.ProjectName,
dict.Username,
projectData => {
var msg;
myself.nextSteps([
() => msg = myself.showMessage('Opening project...'),
() => {
if (projectData.indexOf('<snapdata') === 0) {
myself.rawOpenCloudDataString(projectData);
} else if (
projectData.indexOf('<project') === 0
) {
myself.rawOpenProjectString(projectData);
}
myself.hasChangedMedia = true;
},
() => {
myself.shield.destroy();
myself.shield = null;
msg.destroy();
myself.toggleAppMode(false);
}
]);
},
this.cloudError()
);
} else if (location.hash.substr(0, 4) === '#dl:') {
myself.showMessage('Fetching project\nfrom the cloud...');
// make sure to lowercase the username
dict = myself.cloud.parseDict(location.hash.substr(4));
dict.Username = dict.Username.toLowerCase();
myself.cloud.getPublicProject(
dict.ProjectName,
dict.Username,
projectData => {
myself.saveXMLAs(projectData, dict.ProjectName);
myself.showMessage(
'Saved project\n' + dict.ProjectName,
2
);
},
this.cloudError()
);
} else if (location.hash.substr(0, 6) === '#lang:') {
urlLanguage = location.hash.substr(6);
this.setLanguage(urlLanguage, null, true); // don't persist
this.loadNewProject = true;
} else if (location.hash.substr(0, 7) === '#signup') {
this.createCloudAccount();
}
this.loadNewProject = false;
}
if (this.userLanguage) {
this.loadNewProject = true;
this.setLanguage(this.userLanguage, interpretUrlAnchors);
} else {
interpretUrlAnchors.call(this);
}
world.keyboardFocus = this.stage;
this.warnAboutIE();
};
// IDE_Morph construction
IDE_Morph.prototype.buildPanes = function () {
this.createLogo();
this.createControlBar();
this.createCategories();
this.createPalette();
this.createStage();
this.createSpriteBar();
this.createSpriteEditor();
this.createCorralBar();
this.createCorral();
};
IDE_Morph.prototype.createLogo = function () {
var myself = this;
if (this.logo) {
this.logo.destroy();
}
this.logo = new Morph();
// the logo texture is not loaded dynamically as an image, but instead
// hard-copied here to avoid tainting the world canvas. This lets us
// use Snap's (and Morphic's) color pickers to sense any pixel which
// otherwise would be compromised by annoying browser security.
// this.logo.texture = this.logoURL; // original code, commented out
this.logo.texture = "data:image/png;base64," +
"iVBORw0KGgoAAAANSUhEUgAAACwAAAAYCAYAAACBbx+6AAAKiklEQVRYR5VXe3BU5RX/" +
"ne+7924SwiOEJJvwUCAgCZFBEtRatIlVlATLIwlFsCgdeYWICu1MfbKUabVVtBoDQlUc" +
"FCubEIpAAEUTrGhFGIXAAjZCFdhNQiTkQbK7997vdO7SREAo9P5zZ77HOb9zzu87D8JV" +
"fOyBwGIwEdg5XrcmKRExcoSCNQKgWwXRTYKQDAKUQi1DbASrjzgsdqdM8zc6d6o80LIB" +
"RR6oq1B52SN0pcteL+SUKbCdcw3lCUMsof2amAs0iVRNEoIhZYKoCcTtYBARxUUZ1IMZ" +
"CIZxWDG9oVSv1/tP8Z12ZHAVNMqBdSW9l9uPAGYGoQwicqjQUQsmZ9kLSf8FGyhzzyCB" +
"P8X1kO7TLaoREJuIxCeSzKNhWzRbKhgyRCwJZfcA2UOY+E4QTewZK2Ob2tQhIl6cPLmu" +
"LKLPC+n8O2X/P+CJAXLAXXzpfLD+sqRHesaKF5vbHZtil4bCA98YeO+2f19J0Yl3+wzV" +
"DH0GMz8cE0WxHSH8DZrxhPsX3x7rBO5YUFgI1Um3y8r0sCg8WOZgBQ54YPTJGNCPgehw" +
"qNl/zfTmJoe3Dt9OeN15LgObTUs/JNB9prvA9/mljNvblCkyh+7l6p3AxVxt2JiQalty" +
"IYB5AL5n5qWh1vqVA2cieCWjz+07AXd8C+eZAP71SY8Q6JlzfuajDPFMSkHg7brtSd1w" +
"Vr2hVIymxX97f2IO2nCPP2be0EDaWZuMVttoP2tGBd5/dfCpToHnKMZUvWSJzP5ZNSin" +
"uouv9RXX/MRW9lMgHkekaqCsVZDmZnfD4JMI7LXPPUgHXATaBVEvLDrg7tBgRDbrK9wz" +
"GHwnM0Xrmsg3bT4eC5XV2FzfYnS/fkzK9zU7aQ7MXxbvnxkk8UhYUTcGTGJyMsM/Okw5" +
"s3rVdY2Zs/foe1MyIw8UHjA8oCosEUA1cjw/AA94M/KUMOcQBW8gsptYuXYpa8Cr/aZW" +
"7Sss9Mrhw33swWJkV1eL6uoc6wFPVVRDo3stmDN/xOFAed95EHYps7o/Jb/hrc6QTXt0" +
"/4QzYa1Egd7TyCq3WEgBGkggMyGhbt2bnpyrDO8PJDizAYPbbS21Tw+rXk+BjzIQvhRF" +
"8ub6MlhiF4h6dKU1J1M4xD+xvnc/CaMKpN5LntywqHM9d77vrwCNrCxNG32x0Oxs1lzp" +
"vmtdQVnfe0DArGvsczNskUAaareWDP/SOT+2qKa/DkrtLu14k8HrW+JrsKbf1xFZN3ES" +
"khrbJ7tPxYYMMRpsxQi4ajaVDjnobI8vrslWLLc6186lNYBqX041hiyoDR339ovWNGs7" +
"GA3J+XUFneDGFft+T4zfCsYDm5enrzsfdF7R12lM1jsAfcPgNmJkMqE3AfEMWqYTlVpK" +
"vcDAbSCcEUCcIO6jSyzWSW04a8rXmGAw4yQYg5nQkxi9GHhu6/L0pbnzfbcxoZIUFXd5" +
"2KlEOR5Yfm/cACFduxnCl5zvv70TWN68/YNYauVSi77BNjs2CmDVQKF/WFIyJPTzh48m" +
"GVbwCwK6E+MJJtpBLKUi+1kC3wNShbaF40KDrkM7FrQ0S5PmsyCMd5xAzHMVYRgzzbCV" +
"/jkb4Z66En/WpGuisjryFIkGsFqrWN0XAXx+NQuUpyyJ70VPnz5jfapc7RNS7mltXLly" +
"tj5nzipzbPG+gTrrTzIwQ2guTZmhHUoXxdteGnYkd/6hfUR8cMsr6dM6jcwt+nokkbkL" +
"JBdseWXY6+dH5a6iw3dLUiuYsQJEPwXQurU07b7OM3c9ery3DLceAdHHgvl1xVQYIvzG" +
"AUzshXCqTsP65NtsxioQWgAVw2w/kFLQuGfPykw9a84eqzPV3D2vZgQJ7UEp9YfYDtXa" +
"mhwvLHs5QTRvKU2b3AW4+ND1YOwQQi3cXDJ8be78QwsZGCXAUgFDCdRPET8uGGMBiqlM" +
"WDcBHo9yMkVZ2RQ7d75vEzMGMMmFUqqO0b2H/dMBGym/zBB1Fe6PwBAgvAxgBYMWpuQH" +
"3nLq/5KdrA42f+Y69WXIdFKNA2pcsW+iYLzDjBIQZwHUWlmaNqnTsNzimiywtoFhL2PI" +
"YQTOZfDbAH1B4CwCTSfiJxXTHQTun5gQk/emZ2Aw3XPA8HkywuOKfZXElFJZmjYykik9" +
"LLrSWl1F0iyXIVaFgmqa5rI+NsO680LXJufXzedIo3ZhIv/Bi75qAvwMpEChrnJ52r1d" +
"kSg6MlqStYZBxwFKZ4XpW1ek7XTuTiiq6W+SfA/Ez4FxB0EkbylNG3fem4ljoR1hoFLY" +
"eJ50Kdtq/AcjHG7cFN/XDOu7AWpOzg+kH/DCiJdJXzFLocX7s5wK9+CivZnfne3WM0rD" +
"4ZYwhWO7dbjskD6VSPwOij1MmE2E+srS9LFdmWXu4dtJU2VgOgxgqFDqKc0V827YDCaC" +
"uIgYs1hxMQTdAubbFctJ21YM2z95ti85aGA5gFGsuISIHgNwshurWyKAAxXJy7q5sLA1" +
"qGb1za9/zVnzlyeu6h7TbdbZjmNT3flYN3XBvj+22noRA8cY6CBCFJgSFdQaM6ReMlyi" +
"nEDHKkvTZ3R5f77vTmIuZYlXSNEoEPKZcRiMehAsJ4URsEIJSiPmOQT+EKAWJhoEcIKm" +
"xFxbKottVICwrrI0fTY5Pa5N8iunh2i3w2MGT2lqdhTWlSWNj4kxNp0Nth8Qoe/vSCph" +
"c2rWgYk2EE8gYZNqs1l88feSjN0RPj908AZlo3X78uG1nYBnPHYoHh0dQweh+ZCzdgjx" +
"eU5B0Q0+2MduOtAsY+Paw3qo1daeAXFSFJnLJIm+LIi6a+Hq1ctG+bwvfBq97pueg4TR" +
"42jZi/07KFDh9ib20gpPnbH/4J4ceHLPSuhZc2AeW31tVFT34Fp3ojE50Gi9n5zqn0oj" +
"0HSp0nmpNY/HIzwez1VNF+OLD35gM4W3lqbn/W/5TBRYn7iISPaxFXn7Fvi/9Hgg0tNB" +
"zpRR571mIMtgSbcokXe2PcavKLaCYR4DFBT1qvWfnFZ984IFLU4rugRVoroaqKrKsZ0e" +
"0OmxT3qzrlOC7pZojmbWmcggWylACNh2nBYb9VG4LTy9ZuqOJY/31my9dMziF3vGvDug" +
"pSPb0GWzBdkEwWSdbs/aOPxXZZHIXTAidTbzzj9Srwns35QSgzDfJdjKBon+DM1m5gwi" +
"dAjhL0yahG/+VZnqSt1dazoC9yZDZs6G5dwNbEhcBIXHAdpFZCu2NQ0kmahdWZyoubQj" +
"aLMmbc/Z9pdR6a4Qv5bzYK2ufTwmZGUoTXxnsooxGByWetPTSRPC+yN9zeVC4OBd4gF5" +
"zhsanUY/w4PwiQ19R0plvQWmpckFdd7Lyagrd29i4Nvkgrpix/DTHaboHa1HaCKMDFLh" +
"9/lIo0c9/dmUOKkpXj36+TOuPm+KU8ZYSggfYGHYpMKSP+nwhzrnSnLCWZYOutyYEpm/" +
"fOCLp9268uQXQOpGZnKKTBtLinaYAgJJojZWfCsDBSTlFPfEEzVXy/3/5UCHZlecmh0B" +
"jrfLvBAJPlC/G1PlkNza0OkP4noGW4zVhkaTTAsWsTNnkDP02XSu82oTTPOSCgJvOw85" +
"0xE09MezY9mpQp7i87IHwOJ0IiRcSNOIAdkRmZEJ5D9/VBCtnsd7nAAAAABJRU5ErkJg" +
"gg==";
this.logo.render = function (ctx) {
var gradient = ctx.createLinearGradient(
0,
0,
this.width(),
0
);
gradient.addColorStop(0, 'black');
gradient.addColorStop(0.5, myself.frameColor.toString());
ctx.fillStyle = MorphicPreferences.isFlat ?
myself.frameColor.toString() : gradient;
ctx.fillRect(0, 0, this.width(), this.height());
if (this.cachedTexture) {
this.renderCachedTexture(ctx);
} else if (this.texture) {
this.renderTexture(this.texture, ctx);
}
};
this.logo.renderCachedTexture = function (ctx) {
ctx.drawImage(
this.cachedTexture,
5,
Math.round((this.height() - this.cachedTexture.height) / 2)
);
this.changed();
};
this.logo.mouseClickLeft = function () {
myself.snapMenu();
};
this.logo.color = new Color();
this.logo.setExtent(new Point(200, 28)); // dimensions are fixed
this.add(this.logo);
};
IDE_Morph.prototype.createControlBar = function () {
// assumes the logo has already been created
var padding = 5,
button,
slider,
stopButton,
pauseButton,
startButton,
projectButton,
settingsButton,
stageSizeButton,
appModeButton,
steppingButton,
cloudButton,
x,
colors = [
this.groupColor,
this.frameColor.darker(50),
this.frameColor.darker(50)
],
myself = this;
if (this.controlBar) {
this.controlBar.destroy();
}
this.controlBar = new Morph();
this.controlBar.color = this.frameColor;
this.controlBar.setHeight(this.logo.height()); // height is fixed
// let users manually enforce re-layout when changing orientation
// on mobile devices
this.controlBar.mouseClickLeft = function () {
this.world().fillPage();
};
this.add(this.controlBar);
//smallStageButton
button = new ToggleButtonMorph(
null, //colors,
this, // the IDE is the target
'toggleStageSize',
[
new SymbolMorph('smallStage', 14),
new SymbolMorph('normalStage', 14)
],
() => this.isSmallStage // query
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'stage size\nsmall & normal';
button.fixLayout();
button.refresh();
stageSizeButton = button;
this.controlBar.add(stageSizeButton);
this.controlBar.stageSizeButton = button; // for refreshing
//appModeButton
button = new ToggleButtonMorph(
null, //colors,
this, // the IDE is the target
'toggleAppMode',
[
new SymbolMorph('fullScreen', 14),
new SymbolMorph('normalScreen', 14)
],
() => this.isAppMode // query
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'app & edit\nmodes';
button.fixLayout();
button.refresh();
appModeButton = button;
this.controlBar.add(appModeButton);
this.controlBar.appModeButton = appModeButton; // for refreshing
//steppingButton
button = new ToggleButtonMorph(
null, //colors,
this, // the IDE is the target
'toggleSingleStepping',
[
new SymbolMorph('footprints', 16),
new SymbolMorph('footprints', 16)
],
() => Process.prototype.enableSingleStepping // query
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = new Color(153, 255, 213);
// button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
button.hint = 'Visible stepping';
button.fixLayout();
button.refresh();
steppingButton = button;
this.controlBar.add(steppingButton);
this.controlBar.steppingButton = steppingButton; // for refreshing
// stopButton
button = new ToggleButtonMorph(
null, // colors
this, // the IDE is the target
'stopAllScripts',
[
new SymbolMorph('octagon', 14),
new SymbolMorph('square', 14)
],
() => this.stage ? // query
myself.stage.enableCustomHatBlocks &&
myself.stage.threads.pauseCustomHatBlocks
: true
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = new Color(200, 0, 0);
button.contrast = this.buttonContrast;
// button.hint = 'stop\nevery-\nthing';
button.fixLayout();
button.refresh();
stopButton = button;
this.controlBar.add(stopButton);
this.controlBar.stopButton = stopButton; // for refreshing
//pauseButton
button = new ToggleButtonMorph(
null, //colors,
this, // the IDE is the target
'togglePauseResume',
[
new SymbolMorph('pause', 12),
new SymbolMorph('pointRight', 14)
],
() => this.isPaused() // query
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = new Color(255, 220, 0);
button.contrast = this.buttonContrast;
// button.hint = 'pause/resume\nall scripts';
button.fixLayout();
button.refresh();
pauseButton = button;
this.controlBar.add(pauseButton);
this.controlBar.pauseButton = pauseButton; // for refreshing
// startButton
button = new PushButtonMorph(
this,
'pressStart',
new SymbolMorph('flag', 14)
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = new Color(0, 200, 0);
button.contrast = this.buttonContrast;
// button.hint = 'start green\nflag scripts';
button.fixLayout();
startButton = button;
this.controlBar.add(startButton);
this.controlBar.startButton = startButton;
// steppingSlider
slider = new SliderMorph(
61,
1,
Process.prototype.flashTime * 100 + 1,
6,
'horizontal'
);
slider.action = (num) => {
Process.prototype.flashTime = (num - 1) / 100;
this.controlBar.refreshResumeSymbol();
};
// slider.alpha = MorphicPreferences.isFlat ? 0.1 : 0.3;
slider.color = new Color(153, 255, 213);
slider.alpha = 0.3;
slider.setExtent(new Point(50, 14));
this.controlBar.add(slider);
this.controlBar.steppingSlider = slider;
// projectButton
button = new PushButtonMorph(
this,
'projectMenu',
new SymbolMorph('file', 14)
//'\u270E'
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'open, save, & annotate project';
button.fixLayout();
projectButton = button;
this.controlBar.add(projectButton);
this.controlBar.projectButton = projectButton; // for menu positioning
// settingsButton
button = new PushButtonMorph(
this,
'settingsMenu',
new SymbolMorph('gears', 14)
//'\u2699'
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'edit settings';
button.fixLayout();
settingsButton = button;
this.controlBar.add(settingsButton);
this.controlBar.settingsButton = settingsButton; // for menu positioning
// cloudButton
button = new PushButtonMorph(
this,
'cloudMenu',
new SymbolMorph('cloud', 11)
);
button.corner = 12;
button.color = colors[0];
button.highlightColor = colors[1];
button.pressColor = colors[2];
button.labelMinExtent = new Point(36, 18);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = this.buttonLabelColor;
button.contrast = this.buttonContrast;
// button.hint = 'cloud operations';
button.fixLayout();
cloudButton = button;
this.controlBar.add(cloudButton);
this.controlBar.cloudButton = cloudButton; // for menu positioning
this.controlBar.fixLayout = function () {
x = this.right() - padding;
[stopButton, pauseButton, startButton].forEach(button => {
button.setCenter(myself.controlBar.center());
button.setRight(x);
x -= button.width();
x -= padding;
}
);
x = Math.min(
startButton.left() - (3 * padding + 2 * stageSizeButton.width()),
myself.right() - StageMorph.prototype.dimensions.x *
(myself.isSmallStage ? myself.stageRatio : 1)
);
[stageSizeButton, appModeButton].forEach(button => {
x += padding;
button.setCenter(myself.controlBar.center());
button.setLeft(x);
x += button.width();
}
);
slider.setCenter(myself.controlBar.center());
slider.setRight(stageSizeButton.left() - padding);
steppingButton.setCenter(myself.controlBar.center());
steppingButton.setRight(slider.left() - padding);
settingsButton.setCenter(myself.controlBar.center());
settingsButton.setLeft(this.left());
cloudButton.setCenter(myself.controlBar.center());
cloudButton.setRight(settingsButton.left() - padding);
projectButton.setCenter(myself.controlBar.center());
projectButton.setRight(cloudButton.left() - padding);
this.refreshSlider();
this.updateLabel();
};
this.controlBar.refreshSlider = function () {
if (Process.prototype.enableSingleStepping && !myself.isAppMode) {
slider.fixLayout();
slider.rerender();
slider.show();
} else {
slider.hide();
}
this.refreshResumeSymbol();
};
this.controlBar.refreshResumeSymbol = function () {
var pauseSymbols;
if (Process.prototype.enableSingleStepping &&
Process.prototype.flashTime > 0.5) {
myself.stage.threads.pauseAll(myself.stage);
pauseSymbols = [
new SymbolMorph('pause', 12),
new SymbolMorph('stepForward', 14)
];
} else {
pauseSymbols = [
new SymbolMorph('pause', 12),
new SymbolMorph('pointRight', 14)
];
}
pauseButton.labelString = pauseSymbols;
pauseButton.createLabel();
pauseButton.fixLayout();
pauseButton.refresh();
};
this.controlBar.updateLabel = function () {
var suffix = myself.world().isDevMode ?
' - ' + localize('development mode') : '';
if (this.label) {
this.label.destroy();
}
if (myself.isAppMode) {
return;
}
this.label = new StringMorph(
(myself.projectName || localize('untitled')) + suffix,
14,
'sans-serif',
true,
false,
false,
MorphicPreferences.isFlat ? null : new Point(2, 1),
myself.frameColor.darker(myself.buttonContrast)
);
this.label.color = myself.buttonLabelColor;
this.label.fixLayout();
this.add(this.label);
this.label.setCenter(this.center());
this.label.setLeft(this.settingsButton.right() + padding);
};
};
IDE_Morph.prototype.createCategories = function () {
var myself = this;
if (this.categories) {
this.categories.destroy();
}
this.categories = new Morph();
this.categories.color = this.groupColor;
this.categories.bounds.setWidth(this.paletteWidth);
function addCategoryButton(category) {
var labelWidth = 75,
colors = [
myself.frameColor,
myself.frameColor.darker(50),
SpriteMorph.prototype.blockColor[category]
],
button;
button = new ToggleButtonMorph(
colors,
myself, // the IDE is the target
() => {
myself.currentCategory = category;
myself.categories.children.forEach(each =>
each.refresh()
);
myself.refreshPalette(true);
},
category[0].toUpperCase().concat(category.slice(1)), // label
() => myself.currentCategory === category, // query
null, // env
null, // hint
labelWidth, // minWidth
true // has preview
);
button.corner = 8;
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = myself.buttonLabelColor;
button.fixLayout();
button.refresh();
myself.categories.add(button);
return button;
}
function fixCategoriesLayout() {
var buttonWidth = myself.categories.children[0].width(),
buttonHeight = myself.categories.children[0].height(),
border = 3,
rows = Math.ceil((myself.categories.children.length) / 2),
xPadding = (200 // myself.logo.width()
- border
- buttonWidth * 2) / 3,
yPadding = 2,
l = myself.categories.left(),
t = myself.categories.top(),
i = 0,
row,
col;
myself.categories.children.forEach(button => {
i += 1;
row = Math.ceil(i / 2);
col = 2 - (i % 2);
button.setPosition(new Point(
l + (col * xPadding + ((col - 1) * buttonWidth)),
t + (row * yPadding + ((row - 1) * buttonHeight) + border)
));
});
myself.categories.setHeight(
(rows + 1) * yPadding
+ rows * buttonHeight
+ 2 * border
);
}
SpriteMorph.prototype.categories.forEach(cat => {
if (!contains(['lists', 'other'], cat)) {
addCategoryButton(cat);
}
});
fixCategoriesLayout();
this.add(this.categories);
};
IDE_Morph.prototype.createPalette = function (forSearching) {
// assumes that the logo pane has already been created
// needs the categories pane for layout
if (this.palette) {
this.palette.destroy();
}
if (forSearching) {
this.palette = new ScrollFrameMorph(
null,
null,
this.currentSprite.sliderColor
);
// search toolbar (floating cancel button):
/* commented out for now
this.palette.toolBar = new PushButtonMorph(
this,
() => {
this.refreshPalette();
this.palette.adjustScrollBars();
},
new SymbolMorph("magnifierOutline", 16)
);
this.palette.toolBar.alpha = 0.2;
this.palette.toolBar.padding = 1;
// this.palette.toolBar.hint = 'Cancel';
this.palette.toolBar.labelShadowColor = new Color(140, 140, 140);
this.palette.toolBar.fixLayout();
this.palette.add(this.palette.toolBar);
*/
} else {
this.palette = this.currentSprite.palette(this.currentCategory);
}
this.palette.isDraggable = false;
this.palette.acceptsDrops = true;
this.palette.enableAutoScrolling = false;
this.palette.contents.acceptsDrops = false;
this.palette.reactToDropOf = (droppedMorph, hand) => {
if (droppedMorph instanceof DialogBoxMorph) {
this.world().add(droppedMorph);
} else if (droppedMorph instanceof SpriteMorph) {
this.removeSprite(droppedMorph);
} else if (droppedMorph instanceof SpriteIconMorph) {
droppedMorph.destroy();
this.removeSprite(droppedMorph.object);
} else if (droppedMorph instanceof CostumeIconMorph) {
this.currentSprite.wearCostume(null);
droppedMorph.perish();
} else if (droppedMorph instanceof BlockMorph) {
this.stage.threads.stopAllForBlock(droppedMorph);
if (hand && hand.grabOrigin.origin instanceof ScriptsMorph) {
hand.grabOrigin.origin.clearDropInfo();
hand.grabOrigin.origin.lastDroppedBlock = droppedMorph;
hand.grabOrigin.origin.recordDrop(hand.grabOrigin);
}
droppedMorph.perish();
} else {
droppedMorph.perish();
}
};
this.palette.contents.reactToDropOf = (droppedMorph) => {
// for "undrop" operation
if (droppedMorph instanceof BlockMorph) {
droppedMorph.destroy();
}
};
this.palette.setWidth(this.logo.width());
this.add(this.palette);
return this.palette;
};
IDE_Morph.prototype.createPaletteHandle = function () {
// assumes that the palette has already been created
if (this.paletteHandle) {this.paletteHandle.destroy(); }
this.paletteHandle = new PaletteHandleMorph(this.categories);
this.add(this.paletteHandle);
};
IDE_Morph.prototype.createStage = function () {
// assumes that the logo pane has already been created
if (this.stage) {this.stage.destroy(); }
StageMorph.prototype.frameRate = 0;
this.stage = new StageMorph(this.globalVariables);
this.stage.setExtent(this.stage.dimensions); // dimensions are fixed
if (this.currentSprite instanceof SpriteMorph) {
this.currentSprite.setPosition(
this.stage.center().subtract(
this.currentSprite.extent().divideBy(2)
)
);
this.stage.add(this.currentSprite);
}
this.add(this.stage);
};
IDE_Morph.prototype.createStageHandle = function () {
// assumes that the stage has already been created
if (this.stageHandle) {this.stageHandle.destroy(); }
this.stageHandle = new StageHandleMorph(this.stage);
this.add(this.stageHandle);
};
IDE_Morph.prototype.createSpriteBar = function () {
// assumes that the categories pane has already been created
var rotationStyleButtons = [],
thumbSize = new Point(45, 45),
nameField,
padlock,
thumbnail,
tabCorner = 15,
tabColors = this.tabColors,
tabBar = new AlignmentMorph('row', -tabCorner * 2),
tab,
symbols = ['\u2192', '\u21BB', '\u2194'],
labels = ['don\'t rotate', 'can rotate', 'only face left/right'],
myself = this;
if (this.spriteBar) {
this.spriteBar.destroy();
}
this.spriteBar = new Morph();
this.spriteBar.color = this.frameColor;
this.add(this.spriteBar);
function addRotationStyleButton(rotationStyle) {
var colors = myself.rotationStyleColors,
button;
button = new ToggleButtonMorph(
colors,
myself, // the IDE is the target
() => {
if (myself.currentSprite instanceof SpriteMorph) {
myself.currentSprite.rotationStyle = rotationStyle;
myself.currentSprite.changed();
myself.currentSprite.fixLayout();
myself.currentSprite.rerender();
}
rotationStyleButtons.forEach(each =>
each.refresh()
);
},
symbols[rotationStyle], // label
() => myself.currentSprite instanceof SpriteMorph // query
&& myself.currentSprite.rotationStyle === rotationStyle,
null, // environment
localize(labels[rotationStyle])
);
button.corner = 8;
button.labelMinExtent = new Point(11, 11);
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = myself.buttonLabelColor;
button.fixLayout();
button.refresh();
rotationStyleButtons.push(button);
button.setPosition(myself.spriteBar.position().add(2));
button.setTop(button.top()
+ ((rotationStyleButtons.length - 1) * (button.height() + 2))
);
myself.spriteBar.add(button);
if (myself.currentSprite instanceof StageMorph) {
button.hide();
}
return button;
}
addRotationStyleButton(1);
addRotationStyleButton(2);
addRotationStyleButton(0);
this.rotationStyleButtons = rotationStyleButtons;
thumbnail = new Morph();
thumbnail.isCachingImage = true;
thumbnail.bounds.setExtent(thumbSize);
thumbnail.cachedImage = this.currentSprite.thumbnail(thumbSize);
thumbnail.setPosition(
rotationStyleButtons[0].topRight().add(new Point(5, 3))
);
this.spriteBar.add(thumbnail);
thumbnail.fps = 3;
thumbnail.step = function () {
if (thumbnail.version !== myself.currentSprite.version) {
thumbnail.cachedImage = myself.currentSprite.thumbnail(
thumbSize,
thumbnail.cachedImage
);
thumbnail.changed();
thumbnail.version = myself.currentSprite.version;
}
};
nameField = new InputFieldMorph(this.currentSprite.name);
nameField.setWidth(100); // fixed dimensions
nameField.contrast = 90;
nameField.setPosition(thumbnail.topRight().add(new Point(10, 3)));
this.spriteBar.add(nameField);
this.spriteBar.nameField = nameField;
nameField.fixLayout();
nameField.accept = function () {
var newName = nameField.getValue();
myself.currentSprite.setName(
myself.newSpriteName(newName, myself.currentSprite)
);
nameField.setContents(myself.currentSprite.name);
};
this.spriteBar.reactToEdit = nameField.accept;
// padlock
padlock = new ToggleMorph(
'checkbox',
null,
() => this.currentSprite.isDraggable =
!this.currentSprite.isDraggable,
localize('draggable'),
() => this.currentSprite.isDraggable
);
padlock.label.isBold = false;
padlock.label.setColor(this.buttonLabelColor);
padlock.color = tabColors[2];
padlock.highlightColor = tabColors[0];
padlock.pressColor = tabColors[1];
padlock.tick.shadowOffset = MorphicPreferences.isFlat ?
new Point() : new Point(-1, -1);
padlock.tick.shadowColor = new Color(); // black
padlock.tick.color = this.buttonLabelColor;
padlock.tick.isBold = false;
padlock.tick.fixLayout();
padlock.setPosition(nameField.bottomLeft().add(2));
padlock.fixLayout();
this.spriteBar.add(padlock);
if (this.currentSprite instanceof StageMorph) {
padlock.hide();
}
// tab bar
tabBar.tabTo = function (tabString) {
var active;
myself.currentTab = tabString;
this.children.forEach(each => {
each.refresh();
if (each.state) {active = each; }
});
active.refresh(); // needed when programmatically tabbing
myself.createSpriteEditor();
myself.fixLayout('tabEditor');
};
tab = new TabMorph(
tabColors,
null, // target
() => tabBar.tabTo('scripts'),
localize('Scripts'), // label
() => this.currentTab === 'scripts' // query
);
tab.padding = 3;
tab.corner = tabCorner;
tab.edge = 1;
tab.labelShadowOffset = new Point(-1, -1);
tab.labelShadowColor = tabColors[1];
tab.labelColor = this.buttonLabelColor;
tab.fixLayout();
tabBar.add(tab);
tab = new TabMorph(
tabColors,
null, // target
() => tabBar.tabTo('costumes'),
localize(this.currentSprite instanceof SpriteMorph ?
'Costumes' : 'Backgrounds'
),
() => this.currentTab === 'costumes' // query
);
tab.padding = 3;
tab.corner = tabCorner;
tab.edge = 1;
tab.labelShadowOffset = new Point(-1, -1);
tab.labelShadowColor = tabColors[1];
tab.labelColor = this.buttonLabelColor;
tab.fixLayout();
tabBar.add(tab);
tab = new TabMorph(
tabColors,
null, // target
() => tabBar.tabTo('sounds'),
localize('Sounds'), // label
() => this.currentTab === 'sounds' // query
);
tab.padding = 3;
tab.corner = tabCorner;
tab.edge = 1;
tab.labelShadowOffset = new Point(-1, -1);
tab.labelShadowColor = tabColors[1];
tab.labelColor = this.buttonLabelColor;
tab.fixLayout();
tabBar.add(tab);
tabBar.fixLayout();
tabBar.children.forEach(each =>
each.refresh()
);
this.spriteBar.tabBar = tabBar;
this.spriteBar.add(this.spriteBar.tabBar);
this.spriteBar.fixLayout = function () {
this.tabBar.setLeft(this.left());
this.tabBar.setBottom(this.bottom());
};
};
IDE_Morph.prototype.createSpriteEditor = function () {
// assumes that the logo pane and the stage have already been created
var scripts = this.currentSprite.scripts;
if (this.spriteEditor) {
this.spriteEditor.destroy();
}
if (this.currentTab === 'scripts') {
scripts.isDraggable = false;
scripts.color = this.groupColor;
scripts.cachedTexture = this.scriptsPaneTexture;
this.spriteEditor = new ScrollFrameMorph(
scripts,
null,
this.sliderColor
);
this.spriteEditor.color = this.groupColor;
this.spriteEditor.padding = 10;
this.spriteEditor.growth = 50;
this.spriteEditor.isDraggable = false;
this.spriteEditor.acceptsDrops = false;
this.spriteEditor.contents.acceptsDrops = true;
scripts.scrollFrame = this.spriteEditor;
scripts.updateToolbar();
this.add(this.spriteEditor);
this.spriteEditor.scrollX(this.spriteEditor.padding);
this.spriteEditor.scrollY(this.spriteEditor.padding);
} else if (this.currentTab === 'costumes') {
this.spriteEditor = new WardrobeMorph(
this.currentSprite,
this.sliderColor
);
this.spriteEditor.color = this.groupColor;
this.add(this.spriteEditor);
this.spriteEditor.updateSelection();
this.spriteEditor.acceptsDrops = false;
this.spriteEditor.contents.acceptsDrops = false;
} else if (this.currentTab === 'sounds') {
this.spriteEditor = new JukeboxMorph(
this.currentSprite,
this.sliderColor
);
this.spriteEditor.color = this.groupColor;
this.add(this.spriteEditor);
this.spriteEditor.updateSelection();
this.spriteEditor.acceptDrops = false;
this.spriteEditor.contents.acceptsDrops = false;
} else {
this.spriteEditor = new Morph();
this.spriteEditor.color = this.groupColor;
this.spriteEditor.acceptsDrops = true;
this.spriteEditor.reactToDropOf = (droppedMorph) => {
if (droppedMorph instanceof DialogBoxMorph) {
this.world().add(droppedMorph);
} else if (droppedMorph instanceof SpriteMorph) {
this.removeSprite(droppedMorph);
} else {
droppedMorph.destroy();
}
};
this.add(this.spriteEditor);
}
};
IDE_Morph.prototype.createCorralBar = function () {
// assumes the stage has already been created
var padding = 5,
newbutton,
paintbutton,
cambutton,
colors = [
this.groupColor,
this.frameColor.darker(50),
this.frameColor.darker(50)
];
if (this.corralBar) {
this.corralBar.destroy();
}
this.corralBar = new Morph();
this.corralBar.color = this.frameColor;
this.corralBar.setHeight(this.logo.height()); // height is fixed
this.add(this.corralBar);
// new sprite button
newbutton = new PushButtonMorph(
this,
"addNewSprite",
new SymbolMorph("turtle", 14)
);
newbutton.corner = 12;
newbutton.color = colors[0];
newbutton.highlightColor = colors[1];
newbutton.pressColor = colors[2];
newbutton.labelMinExtent = new Point(36, 18);
newbutton.padding = 0;
newbutton.labelShadowOffset = new Point(-1, -1);
newbutton.labelShadowColor = colors[1];
newbutton.labelColor = this.buttonLabelColor;
newbutton.contrast = this.buttonContrast;
newbutton.hint = "add a new Turtle sprite";
newbutton.fixLayout();
newbutton.setCenter(this.corralBar.center());
newbutton.setLeft(this.corralBar.left() + padding);
this.corralBar.add(newbutton);
paintbutton = new PushButtonMorph(
this,
"paintNewSprite",
new SymbolMorph("brush", 15)
);
paintbutton.corner = 12;
paintbutton.color = colors[0];
paintbutton.highlightColor = colors[1];
paintbutton.pressColor = colors[2];
paintbutton.labelMinExtent = new Point(36, 18);
paintbutton.padding = 0;
paintbutton.labelShadowOffset = new Point(-1, -1);
paintbutton.labelShadowColor = colors[1];
paintbutton.labelColor = this.buttonLabelColor;
paintbutton.contrast = this.buttonContrast;
paintbutton.hint = "paint a new sprite";
paintbutton.fixLayout();
paintbutton.setCenter(this.corralBar.center());
paintbutton.setLeft(
this.corralBar.left() + padding + newbutton.width() + padding
);
this.corralBar.add(paintbutton);
if (CamSnapshotDialogMorph.prototype.enableCamera) {
cambutton = new PushButtonMorph(
this,
"newCamSprite",
new SymbolMorph("camera", 15)
);
cambutton.corner = 12;
cambutton.color = colors[0];
cambutton.highlightColor = colors[1];
cambutton.pressColor = colors[2];
cambutton.labelMinExtent = new Point(36, 18);
cambutton.padding = 0;
cambutton.labelShadowOffset = new Point(-1, -1);
cambutton.labelShadowColor = colors[1];
cambutton.labelColor = this.buttonLabelColor;
cambutton.contrast = this.buttonContrast;
cambutton.hint = "take a camera snapshot and\n" +
"import it as a new sprite";
cambutton.fixLayout();
cambutton.setCenter(this.corralBar.center());
cambutton.setLeft(
this.corralBar.left() +
padding +
newbutton.width() +
padding +
paintbutton.width() +
padding
);
this.corralBar.add(cambutton);
document.addEventListener(
'cameraDisabled',
event => {
cambutton.disable();
cambutton.hint =
CamSnapshotDialogMorph.prototype.notSupportedMessage;
}
);
}
};
IDE_Morph.prototype.createCorral = function () {
// assumes the corral bar has already been created
var frame, padding = 5, myself = this;
this.createStageHandle();
this.createPaletteHandle();
if (this.corral) {
this.corral.destroy();
}
this.corral = new Morph();
this.corral.color = this.groupColor;
this.add(this.corral);
this.corral.stageIcon = new SpriteIconMorph(this.stage);
this.corral.stageIcon.isDraggable = false;
this.corral.add(this.corral.stageIcon);
frame = new ScrollFrameMorph(null, null, this.sliderColor);
frame.acceptsDrops = false;
frame.contents.acceptsDrops = false;
frame.contents.wantsDropOf = (morph) => morph instanceof SpriteIconMorph;
frame.contents.reactToDropOf = (spriteIcon) =>
this.corral.reactToDropOf(spriteIcon);
frame.alpha = 0;
this.sprites.asArray().forEach(morph => {
if (!morph.isTemporary) {
frame.contents.add(new SpriteIconMorph(morph));
}
});
this.corral.frame = frame;
this.corral.add(frame);
this.corral.fixLayout = function () {
this.stageIcon.setCenter(this.center());
this.stageIcon.setLeft(this.left() + padding);
this.frame.setLeft(this.stageIcon.right() + padding);
this.frame.setExtent(new Point(
this.right() - this.frame.left(),
this.height()
));
this.arrangeIcons();
this.refresh();
};
this.corral.arrangeIcons = function () {
var x = this.frame.left(),
y = this.frame.top(),
max = this.frame.right(),
start = this.frame.left();
this.frame.contents.children.forEach(icon => {
var w = icon.width();
if (x + w > max) {
x = start;
y += icon.height(); // they're all the same
}
icon.setPosition(new Point(x, y));
x += w;
});
this.frame.contents.adjustBounds();
};
this.corral.addSprite = function (sprite) {
this.frame.contents.add(new SpriteIconMorph(sprite));
this.fixLayout();
};
this.corral.refresh = function () {
this.stageIcon.refresh();
this.frame.contents.children.forEach(icon =>
icon.refresh()
);
};
this.corral.wantsDropOf = (morph) => morph instanceof SpriteIconMorph;
this.corral.reactToDropOf = function (spriteIcon) {
var idx = 1,
pos = spriteIcon.position();
spriteIcon.destroy();
this.frame.contents.children.forEach(icon => {
if (pos.gt(icon.position()) || pos.y > icon.bottom()) {
idx += 1;
}
});
myself.sprites.add(spriteIcon.object, idx);
myself.createCorral();
myself.fixLayout();
};
};
// IDE_Morph layout
IDE_Morph.prototype.fixLayout = function (situation) {
// situation is a string, i.e.
// 'selectSprite' or 'refreshPalette' or 'tabEditor'
var padding = this.padding,
flag,
maxPaletteWidth;
if (situation !== 'refreshPalette') {
// controlBar
this.controlBar.setPosition(this.logo.topRight());
this.controlBar.setWidth(this.right() - this.controlBar.left());
this.controlBar.fixLayout();
// categories
this.categories.setLeft(this.logo.left());
this.categories.setTop(this.logo.bottom());
this.categories.setWidth(this.paletteWidth);
}
// palette
this.palette.setLeft(this.logo.left());
this.palette.setTop(this.categories.bottom());
this.palette.setHeight(this.bottom() - this.palette.top());
this.palette.setWidth(this.paletteWidth);
if (situation !== 'refreshPalette') {
// stage
if (this.isEmbedMode) {
this.stage.setScale(Math.floor(Math.min(
this.width() / this.stage.dimensions.x,
this.height() / this.stage.dimensions.y
) * 100) / 100);
flag = this.embedPlayButton.flag;
flag.size = Math.floor(Math.min(
this.width(), this.height())) / 5;
flag.setWidth(flag.size);
flag.setHeight(flag.size);
this.embedPlayButton.size = flag.size * 1.6;
this.embedPlayButton.setWidth(this.embedPlayButton.size);
this.embedPlayButton.setHeight(this.embedPlayButton.size);
if (this.embedOverlay) {
this.embedOverlay.setExtent(this.extent());
}
this.stage.setCenter(this.center());
this.embedPlayButton.setCenter(this.stage.center());
flag.setCenter(this.embedPlayButton.center());
flag.setLeft(flag.left() + flag.size * 0.1); // account for slight asymmetry
} else if (this.isAppMode) {
this.stage.setScale(Math.floor(Math.min(
(this.width() - padding * 2) / this.stage.dimensions.x,
(this.height() - this.controlBar.height() * 2 - padding * 2)
/ this.stage.dimensions.y
) * 10) / 10);
this.stage.setCenter(this.center());
} else {
this.stage.setScale(this.isSmallStage ? this.stageRatio : 1);
this.stage.setTop(this.logo.bottom() + padding);
this.stage.setRight(this.right());
maxPaletteWidth = Math.max(
200,
this.width() -
this.stage.width() -
this.spriteBar.tabBar.width() -
(this.padding * 2)
);
if (this.paletteWidth > maxPaletteWidth) {
this.paletteWidth = maxPaletteWidth;
this.fixLayout();
}
this.stageHandle.fixLayout();
this.paletteHandle.fixLayout();
}
// spriteBar
this.spriteBar.setLeft(this.paletteWidth + padding);
this.spriteBar.setTop(this.logo.bottom() + padding);
this.spriteBar.setExtent(new Point(
Math.max(0, this.stage.left() - padding - this.spriteBar.left()),
this.categories.bottom() - this.spriteBar.top() - padding
));
this.spriteBar.fixLayout();
// spriteEditor
if (this.spriteEditor.isVisible) {
this.spriteEditor.setPosition(this.spriteBar.bottomLeft());
this.spriteEditor.setExtent(new Point(
this.spriteBar.width(),
this.bottom() - this.spriteEditor.top()
));
}
// corralBar
this.corralBar.setLeft(this.stage.left());
this.corralBar.setTop(this.stage.bottom() + padding);
this.corralBar.setWidth(this.stage.width());
// corral
if (!contains(['selectSprite', 'tabEditor'], situation)) {
this.corral.setPosition(this.corralBar.bottomLeft());
this.corral.setWidth(this.stage.width());
this.corral.setHeight(this.bottom() - this.corral.top());
this.corral.fixLayout();
}
}
};
IDE_Morph.prototype.setProjectName = function (string) {
this.projectName = string.replace(/['"]/g, ''); // filter quotation marks
this.hasChangedMedia = true;
this.controlBar.updateLabel();
};
// IDE_Morph resizing
IDE_Morph.prototype.setExtent = function (point) {
var padding = new Point(430, 110),
minExt,
ext,
maxWidth,
minWidth,
maxHeight,
minRatio,
maxRatio;
// determine the minimum dimensions making sense for the current mode
if (this.isAppMode) {
if (this.isEmbedMode) {
minExt = new Point(100, 100);
} else {
minExt = StageMorph.prototype.dimensions.add(
this.controlBar.height() + 10
);
}
} else {
if (this.stageRatio > 1) {
minExt = padding.add(StageMorph.prototype.dimensions);
} else {
minExt = padding.add(
StageMorph.prototype.dimensions.multiplyBy(this.stageRatio)
);
}
}
ext = point.max(minExt);
// adjust stage ratio if necessary
maxWidth = ext.x -
(200 + this.spriteBar.tabBar.width() + (this.padding * 2));
minWidth = SpriteIconMorph.prototype.thumbSize.x * 3;
maxHeight = (ext.y - SpriteIconMorph.prototype.thumbSize.y * 3.5);
minRatio = minWidth / this.stage.dimensions.x;
maxRatio = Math.min(
(maxWidth / this.stage.dimensions.x),
(maxHeight / this.stage.dimensions.y)
);
this.stageRatio = Math.min(maxRatio, Math.max(minRatio, this.stageRatio));
// apply
IDE_Morph.uber.setExtent.call(this, ext);
this.fixLayout();
};
// IDE_Morph events
IDE_Morph.prototype.reactToWorldResize = function (rect) {
if (this.isAutoFill) {
this.setPosition(rect.origin);
this.setExtent(rect.extent());
}
if (this.filePicker) {
document.body.removeChild(this.filePicker);
this.filePicker = null;
}
};
IDE_Morph.prototype.droppedImage = function (aCanvas, name) {
var costume = new Costume(
aCanvas,
this.currentSprite.newCostumeName(
name ? name.split('.')[0] : '' // up to period
)
);
if (costume.isTainted()) {
this.inform(
'Unable to import this image',
'The picture you wish to import has been\n' +
'tainted by a restrictive cross-origin policy\n' +
'making it unusable for costumes in Snap!. \n\n' +
'Try downloading this picture first to your\n' +
'computer, and import it from there.'
);
return;
}
this.currentSprite.addCostume(costume);
this.currentSprite.wearCostume(costume);
this.spriteBar.tabBar.tabTo('costumes');
this.hasChangedMedia = true;
};
IDE_Morph.prototype.droppedSVG = function (anImage, name) {
var costume = new SVG_Costume(anImage, name.split('.')[0]);
this.currentSprite.addCostume(costume);
this.currentSprite.wearCostume(costume);
this.spriteBar.tabBar.tabTo('costumes');
this.hasChangedMedia = true;
};
IDE_Morph.prototype.droppedAudio = function (anAudio, name) {
if (anAudio.src.indexOf('data:audio') !== 0) {
// fetch and base 64 encode samples using FileReader
this.getURL(
anAudio.src,
blob => {
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
var base64 = reader.result;
base64 = 'data:audio/ogg;base64,' +
base64.split(',')[1];
anAudio.src = base64;
this.droppedAudio(anAudio, name);
};
},
'blob'
);
} else {
this.currentSprite.addSound(anAudio, name.split('.')[0]); // up to '.'
this.spriteBar.tabBar.tabTo('sounds');
this.hasChangedMedia = true;
}
};
IDE_Morph.prototype.droppedText = function (aString, name, fileType) {
var lbl = name ? name.split('.')[0] : '',
ext = name ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : '';
// check for Snap specific files, projects, libraries, sprites, scripts
if (aString.indexOf('<project') === 0) {
location.hash = '';
return this.openProjectString(aString);
}
if (aString.indexOf('<snapdata') === 0) {
location.hash = '';
return this.openCloudDataString(aString);
}
if (aString.indexOf('<blocks') === 0) {
return this.openBlocksString(aString, lbl, true);
}
if (aString.indexOf('<sprites') === 0) {
return this.openSpritesString(aString);
}
if (aString.indexOf('<media') === 0) {
return this.openMediaString(aString);
}
if (aString.indexOf('<script') === 0) {
return this.openScriptString(aString);
}
// check for encoded data-sets, CSV, JSON
if (fileType.indexOf('csv') !== -1 || ext === 'csv') {
return this.openDataString(aString, lbl, 'csv');
}
if (fileType.indexOf('json') !== -1 || ext === 'json') {
return this.openDataString(aString, lbl, 'json');
}
// import as plain text data
this.openDataString(aString, lbl, 'text');
};
IDE_Morph.prototype.droppedBinary = function (anArrayBuffer, name) {
// dynamically load ypr->Snap!
var ypr = document.getElementById('ypr'),
myself = this,
suffix = name.substring(name.length - 3);
if (suffix.toLowerCase() !== 'ypr') {return; }
function loadYPR(buffer, lbl) {
var reader = new sb.Reader(),
pname = lbl.split('.')[0]; // up to period
reader.onload = function (info) {
myself.droppedText(new sb.XMLWriter().write(pname, info));
};
reader.readYPR(new Uint8Array(buffer));
}
if (!ypr) {
ypr = document.createElement('script');
ypr.id = 'ypr';
ypr.onload = function () {loadYPR(anArrayBuffer, name); };
document.head.appendChild(ypr);
ypr.src = this.resourceURL('src', 'ypr.js');
} else {
loadYPR(anArrayBuffer, name);
}
};
// IDE_Morph button actions
IDE_Morph.prototype.refreshPalette = function (shouldIgnorePosition) {
var oldTop = this.palette.contents.top();
this.createPalette();
if (this.isAppMode) {
this.palette.hide();
return;
}
this.fixLayout('refreshPalette');
if (!shouldIgnorePosition) {
this.palette.contents.setTop(oldTop);
}
};
IDE_Morph.prototype.pressStart = function () {
if (this.world().currentKey === 16) { // shiftClicked
this.toggleFastTracking();
} else {
this.stage.threads.pauseCustomHatBlocks = false;
this.controlBar.stopButton.refresh();
this.runScripts();
}
};
IDE_Morph.prototype.toggleFastTracking = function () {
if (this.stage.isFastTracked) {
this.stopFastTracking();
} else {
this.startFastTracking();
}
};
IDE_Morph.prototype.toggleVariableFrameRate = function () {
if (StageMorph.prototype.frameRate) {
StageMorph.prototype.frameRate = 0;
this.stage.fps = 0;
} else {
StageMorph.prototype.frameRate = 30;
this.stage.fps = 30;
}
};
IDE_Morph.prototype.toggleSingleStepping = function () {
this.stage.threads.toggleSingleStepping();
this.controlBar.steppingButton.refresh();
this.controlBar.refreshSlider();
};
IDE_Morph.prototype.toggleCameraSupport = function () {
CamSnapshotDialogMorph.prototype.enableCamera =
!CamSnapshotDialogMorph.prototype.enableCamera;
this.spriteBar.tabBar.tabTo(this.currentTab);
this.createCorralBar();
this.fixLayout();
};
IDE_Morph.prototype.startFastTracking = function () {
this.stage.isFastTracked = true;
this.stage.fps = 0;
this.controlBar.startButton.labelString = new SymbolMorph('flash', 14);
this.controlBar.startButton.createLabel();
this.controlBar.startButton.fixLayout();
this.controlBar.startButton.rerender();
};
IDE_Morph.prototype.stopFastTracking = function () {
this.stage.isFastTracked = false;
this.stage.fps = this.stage.frameRate;
this.controlBar.startButton.labelString = new SymbolMorph('flag', 14);
this.controlBar.startButton.createLabel();
this.controlBar.startButton.fixLayout();
this.controlBar.startButton.rerender();
};
IDE_Morph.prototype.runScripts = function () {
this.stage.fireGreenFlagEvent();
};
IDE_Morph.prototype.togglePauseResume = function () {
if (this.stage.threads.isPaused()) {
this.stage.threads.resumeAll(this.stage);
} else {
this.stage.threads.pauseAll(this.stage);
}
this.controlBar.pauseButton.refresh();
};
IDE_Morph.prototype.isPaused = function () {
if (!this.stage) {return false; }
return this.stage.threads.isPaused();
};
IDE_Morph.prototype.stopAllScripts = function () {
if (this.stage.enableCustomHatBlocks) {
this.stage.threads.pauseCustomHatBlocks =
!this.stage.threads.pauseCustomHatBlocks;
} else {
this.stage.threads.pauseCustomHatBlocks = false;
}
this.controlBar.stopButton.refresh();
this.stage.fireStopAllEvent();
};
IDE_Morph.prototype.selectSprite = function (sprite) {
// prevent switching to another sprite if a block editor is open
// so local blocks of different sprites don't mix
if (
detect(
this.world().children,
morph => morph instanceof BlockEditorMorph ||
morph instanceof BlockDialogMorph
)
) {
return;
}
if (this.currentSprite && this.currentSprite.scripts.focus) {
this.currentSprite.scripts.focus.stopEditing();
}
this.currentSprite = sprite;
this.createPalette();
this.createSpriteBar();
this.createSpriteEditor();
this.corral.refresh();
this.fixLayout('selectSprite');
this.currentSprite.scripts.fixMultiArgs();
};
// IDE_Morph retina display support
IDE_Morph.prototype.toggleRetina = function () {
if (isRetinaEnabled()) {
disableRetinaSupport();
} else {
enableRetinaSupport();
}
this.world().fillPage();
IDE_Morph.prototype.scriptsPaneTexture = this.scriptsTexture();
this.stage.clearPenTrails();
this.refreshIDE();
};
// IDE_Morph skins
IDE_Morph.prototype.defaultDesign = function () {
this.setDefaultDesign();
this.refreshIDE();
this.removeSetting('design');
};
IDE_Morph.prototype.flatDesign = function () {
this.setFlatDesign();
this.refreshIDE();
this.saveSetting('design', 'flat');
};
IDE_Morph.prototype.refreshIDE = function () {
var projectData;
if (Process.prototype.isCatchingErrors) {
try {
projectData = this.serializer.serialize(this.stage);
} catch (err) {
this.showMessage('Serialization failed: ' + err);
}
} else {
projectData = this.serializer.serialize(this.stage);
}
SpriteMorph.prototype.initBlocks();
this.buildPanes();
this.fixLayout();
if (this.loadNewProject) {
this.newProject();
} else {
this.openProjectString(projectData);
}
};
// IDE_Morph settings persistance
IDE_Morph.prototype.applySavedSettings = function () {
var design = this.getSetting('design'),
zoom = this.getSetting('zoom'),
language = this.getSetting('language'),
click = this.getSetting('click'),
longform = this.getSetting('longform'),
longurls = this.getSetting('longurls'),
plainprototype = this.getSetting('plainprototype'),
keyboard = this.getSetting('keyboard'),
tables = this.getSetting('tables'),
tableLines = this.getSetting('tableLines'),
autoWrapping = this.getSetting('autowrapping');
// design
if (design === 'flat') {
this.setFlatDesign();
} else {
this.setDefaultDesign();
}
// blocks zoom
if (zoom) {
SyntaxElementMorph.prototype.setScale(Math.min(zoom, 12));
CommentMorph.prototype.refreshScale();
SpriteMorph.prototype.initBlocks();
}
// language
if (language && language !== 'en') {
this.userLanguage = language;
} else {
this.userLanguage = null;
}
// click
if (click && !BlockMorph.prototype.snapSound) {
BlockMorph.prototype.toggleSnapSound();
}
// long form
if (longform) {
InputSlotDialogMorph.prototype.isLaunchingExpanded = true;
}
// project data in URLs
if (longurls) {
this.projectsInURLs = true;
} else {
this.projectsInURLs = false;
}
// keyboard editing
if (keyboard === 'false') {
ScriptsMorph.prototype.enableKeyboard = false;
} else {
ScriptsMorph.prototype.enableKeyboard = true;
}
// tables
if (tables === 'false') {
List.prototype.enableTables = false;
} else {
List.prototype.enableTables = true;
}
// tableLines
if (tableLines) {
TableMorph.prototype.highContrast = true;
} else {
TableMorph.prototype.highContrast = false;
}
// nested auto-wrapping
if (autoWrapping === 'false') {
ScriptsMorph.prototype.enableNestedAutoWrapping = false;
} else {
ScriptsMorph.prototype.enableNestedAutoWrapping = true;
}
// plain prototype labels
if (plainprototype) {
BlockLabelPlaceHolderMorph.prototype.plainLabel = true;
}
};
IDE_Morph.prototype.saveSetting = function (key, value) {
if (!this.savingPreferences) {
return;
}
if (this.hasLocalStorage()) {
localStorage['-snap-setting-' + key] = value;
}
};
IDE_Morph.prototype.getSetting = function (key) {
if (this.hasLocalStorage()) {
return localStorage['-snap-setting-' + key];
}
return null;
};
IDE_Morph.prototype.removeSetting = function (key) {
if (this.hasLocalStorage()) {
delete localStorage['-snap-setting-' + key];
}
};
IDE_Morph.prototype.hasLocalStorage = function () {
// checks whether localStorage is available,
// this kludgy try/catch mechanism is needed
// because Safari 11 is paranoid about accessing
// localstorage from the file:// protocol
try {
return !isNil(localStorage);
} catch (err) {
return false;
}
};
// IDE_Morph sprite list access
IDE_Morph.prototype.addNewSprite = function () {
var sprite = new SpriteMorph(this.globalVariables),
rnd = Process.prototype.reportBasicRandom;
sprite.name = this.newSpriteName(sprite.name);
sprite.setCenter(this.stage.center());
this.stage.add(sprite);
sprite.fixLayout();
sprite.rerender();
// randomize sprite properties
sprite.setColorComponentHSVA(0, rnd.call(this, 0, 100));
sprite.setColorComponentHSVA(1, 100);
sprite.setColorComponentHSVA(2, rnd.call(this, 50, 100));
sprite.setXPosition(rnd.call(this, -220, 220));
sprite.setYPosition(rnd.call(this, -160, 160));
if (this.world().currentKey === 16) { // shift-click
sprite.turn(rnd.call(this, 1, 360));
}
this.sprites.add(sprite);
this.corral.addSprite(sprite);
this.selectSprite(sprite);
};
IDE_Morph.prototype.paintNewSprite = function () {
var sprite = new SpriteMorph(this.globalVariables),
cos = new Costume();
sprite.name = this.newSpriteName(sprite.name);
sprite.setCenter(this.stage.center());
this.stage.add(sprite);
this.sprites.add(sprite);
this.corral.addSprite(sprite);
this.selectSprite(sprite);
cos.edit(
this.world(),
this,
true,
() => this.removeSprite(sprite),
() => {
sprite.addCostume(cos);
sprite.wearCostume(cos);
}
);
};
IDE_Morph.prototype.newCamSprite = function () {
var sprite = new SpriteMorph(this.globalVariables),
camDialog;
sprite.name = this.newSpriteName(sprite.name);
sprite.setCenter(this.stage.center());
this.stage.add(sprite);
this.sprites.add(sprite);
this.corral.addSprite(sprite);
this.selectSprite(sprite);
camDialog = new CamSnapshotDialogMorph(
this,
sprite,
() => this.removeSprite(sprite),
function (costume) { // needs to be "function" to it can access "this"
sprite.addCostume(costume);
sprite.wearCostume(costume);
this.close();
});
camDialog.popUp(this.world());
};
IDE_Morph.prototype.recordNewSound = function () {
var soundRecorder;
soundRecorder = new SoundRecorderDialogMorph(
audio => {
var sound;
if (audio) {
sound = this.currentSprite.addSound(
audio,
this.newSoundName('recording')
);
this.makeSureRecordingIsMono(sound);
this.spriteBar.tabBar.tabTo('sounds');
this.hasChangedMedia = true;
}
});
soundRecorder.key = 'microphone';
soundRecorder.popUp(this.world());
};
IDE_Morph.prototype.makeSureRecordingIsMono = function (sound) {
// private and temporary, a horrible kludge to work around browsers'
// reluctance to implement audio recording constraints that let us
// record sound in mono only. As of January 2020 the audio channelCount
// constraint only works in Firefox, hence this terrible function to
// force convert a stereo sound to mono for Chrome.
// If this code is still here next year, something is very wrong.
// -Jens
decodeSound(sound, makeMono);
function decodeSound(sound, callback) {
var base64, binaryString, len, bytes, i, arrayBuffer, audioCtx;
if (sound.audioBuffer) {
return callback (sound);
}
base64 = sound.audio.src.split(',')[1];
binaryString = window.atob(base64);
len = binaryString.length;
bytes = new Uint8Array(len);
for (i = 0; i < len; i += 1) {
bytes[i] = binaryString.charCodeAt(i);
}
arrayBuffer = bytes.buffer;
audioCtx = Note.prototype.getAudioContext();
sound.isDecoding = true;
audioCtx.decodeAudioData(
arrayBuffer,
buffer => {
sound.audioBuffer = buffer;
return callback (sound);
},
err => {throw err; }
);
}
function makeMono(sound) {
var samples, audio, blob, reader;
if (sound.audioBuffer.numberOfChannels === 1) {return; }
samples = sound.audioBuffer.getChannelData(0);
audio = new Audio();
blob = new Blob(
[
audioBufferToWav(
encodeSound(samples, 44100).audioBuffer
)
],
{type: "audio/wav"}
);
reader = new FileReader();
reader.onload = () => {
audio.src = reader.result;
sound.audio = audio; // .... aaaand we're done!
sound.audioBuffer = null;
sound.cachedSamples = null;
sound.isDecoding = false;
// console.log('made mono', sound);
};
reader.readAsDataURL(blob);
}
function encodeSound(samples, rate) {
var ctx = Note.prototype.getAudioContext(),
frameCount = samples.length,
arrayBuffer = ctx.createBuffer(1, frameCount, +rate || 44100),
i,
source;
if (!arrayBuffer.copyToChannel) {
arrayBuffer.copyToChannel = function (src, channel) {
var buffer = this.getChannelData(channel);
for (i = 0; i < src.length; i += 1) {
buffer[i] = src[i];
}
};
}
arrayBuffer.copyToChannel(
Float32Array.from(samples),
0,
0
);
source = ctx.createBufferSource();
source.buffer = arrayBuffer;
source.audioBuffer = source.buffer;
return source;
}
function audioBufferToWav(buffer, opt) {
var sampleRate = buffer.sampleRate,
format = (opt || {}).float32 ? 3 : 1,
bitDepth = format === 3 ? 32 : 16,
result;
result = buffer.getChannelData(0);
return encodeWAV(result, format, sampleRate, 1, bitDepth);
}
function encodeWAV(
samples,
format,
sampleRate,
numChannels,
bitDepth
) {
var bytesPerSample = bitDepth / 8,
blockAlign = numChannels * bytesPerSample,
buffer = new ArrayBuffer(44 + samples.length * bytesPerSample),
view = new DataView(buffer);
function writeFloat32(output, offset, input) {
for (var i = 0; i < input.length; i += 1, offset += 4) {
output.setFloat32(offset, input[i], true);
}
}
function floatTo16BitPCM(output, offset, input) {
var i, s;
for (i = 0; i < input.length; i += 1, offset += 2) {
s = Math.max(-1, Math.min(1, input[i]));
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
}
}
function writeString(view, offset, string) {
for (var i = 0; i < string.length; i += 1) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
writeString(view, 0, 'RIFF'); // RIFF identifier
// RIFF chunk length:
view.setUint32(4, 36 + samples.length * bytesPerSample, true);
writeString(view, 8, 'WAVE'); // RIFF type
writeString(view, 12, 'fmt '); // format chunk identifier
view.setUint32(16, 16, true); // format chunk length
view.setUint16(20, format, true); // sample format (raw)
view.setUint16(22, numChannels, true); // channel count
view.setUint32(24, sampleRate, true); // sample rate
// byte rate (sample rate * block align):
view.setUint32(28, sampleRate * blockAlign, true);
// block align (channel count * bytes per sample):
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitDepth, true); // bits per sample
writeString(view, 36, 'data'); // data chunk identifier
// data chunk length:
view.setUint32(40, samples.length * bytesPerSample, true);
if (format === 1) { // Raw PCM
floatTo16BitPCM(view, 44, samples);
} else {
writeFloat32(view, 44, samples);
}
return buffer;
}
};
IDE_Morph.prototype.duplicateSprite = function (sprite) {
var duplicate = sprite.fullCopy();
duplicate.isDown = false;
duplicate.setPosition(this.world().hand.position());
duplicate.appearIn(this);
duplicate.keepWithin(this.stage);
duplicate.isDown = sprite.isDown;
this.selectSprite(duplicate);
};
IDE_Morph.prototype.instantiateSprite = function (sprite) {
var instance = sprite.fullCopy(true),
hats = instance.allHatBlocksFor('__clone__init__');
instance.isDown = false;
instance.appearIn(this);
if (hats.length) {
instance.initClone(hats);
} else {
instance.setPosition(this.world().hand.position());
instance.keepWithin(this.stage);
}
instance.isDown = sprite.isDown;
this.selectSprite(instance);
};
IDE_Morph.prototype.removeSprite = function (sprite) {
var idx;
sprite.parts.slice().forEach(part =>
this.removeSprite(part)
);
idx = this.sprites.asArray().indexOf(sprite) + 1;
this.stage.threads.stopAllForReceiver(sprite);
sprite.corpsify();
sprite.destroy();
this.stage.watchers().forEach(watcher => {
if (watcher.object() === sprite) {
watcher.destroy();
}
});
if (idx > 0) {
this.sprites.remove(idx);
}
this.createCorral();
this.fixLayout();
this.currentSprite = detect(
this.stage.children,
morph => morph instanceof SpriteMorph && !morph.isTemporary
) || this.stage;
this.selectSprite(this.currentSprite);
};
IDE_Morph.prototype.newSoundName = function (name) {
var lastSound = this.currentSprite.sounds.at(
this.currentSprite.sounds.length()
);
return this.newName(
name || lastSound.name,
this.currentSprite.sounds.asArray().map(eachSound =>
eachSound.name
)
);
};
IDE_Morph.prototype.newSpriteName = function (name, ignoredSprite) {
var all = this.sprites.asArray().concat(this.stage).filter(each =>
each !== ignoredSprite
).map(each => each.name);
return this.newName(name, all);
};
IDE_Morph.prototype.newName = function (name, elements) {
var ix = name.indexOf('('),
stem = (ix < 0) ? name : name.substring(0, ix),
count = 1,
newName = stem;
while (contains(elements, newName)) {
count += 1;
newName = stem + '(' + count + ')';
}
return newName;
};
// IDE_Morph deleting scripts
IDE_Morph.prototype.removeBlock = function (aBlock, justThis) {
this.stage.threads.stopAllForBlock(aBlock);
aBlock.destroy(justThis);
};
// IDE_Morph menus
IDE_Morph.prototype.userMenu = function () {
var menu = new MenuMorph(this);
// menu.addItem('help', 'nop');
return menu;
};
IDE_Morph.prototype.snapMenu = function () {
var menu,
world = this.world();
menu = new MenuMorph(this);
menu.addItem('About...', 'aboutSnap');
menu.addLine();
menu.addItem(
'Reference manual',
() => {
var url = this.resourceURL('help', 'SnapManual.pdf');
window.open(url, 'SnapReferenceManual');
}
);
menu.addItem(
'Snap! website',
() => window.open('https://snap.berkeley.edu/', 'SnapWebsite')
);
menu.addItem(
'Download source',
() => window.open(
'https://github.com/jmoenig/Snap/releases/latest',
'SnapSource'
)
);
if (world.isDevMode) {
menu.addLine();
menu.addItem(
'Switch back to user mode',
'switchToUserMode',
'disable deep-Morphic\ncontext menus'
+ '\nand show user-friendly ones',
new Color(0, 100, 0)
);
} else if (world.currentKey === 16) { // shift-click
menu.addLine();
menu.addItem(
'Switch to dev mode',
'switchToDevMode',
'enable Morphic\ncontext menus\nand inspectors,'
+ '\nnot user-friendly!',
new Color(100, 0, 0)
);
}
menu.popup(world, this.logo.bottomLeft());
};
IDE_Morph.prototype.cloudMenu = function () {
var menu,
world = this.world(),
pos = this.controlBar.cloudButton.bottomLeft(),
shiftClicked = (world.currentKey === 16);
if (location.protocol === 'file:' && !shiftClicked) {
this.showMessage('cloud unavailable without a web server.');
return;
}
menu = new MenuMorph(this);
if (shiftClicked) {
menu.addItem(
'url...',
'setCloudURL',
null,
new Color(100, 0, 0)
);
menu.addLine();
}
if (!this.cloud.username) {
menu.addItem(
'Login...',
'initializeCloud'
);
menu.addItem(
'Signup...',
'createCloudAccount'
);
menu.addItem(
'Reset Password...',
'resetCloudPassword'
);
menu.addItem(
'Resend Verification Email...',
'resendVerification'
);
} else {
menu.addItem(
localize('Logout') + ' ' + this.cloud.username,
'logout'
);
menu.addItem(
'Change Password...',
'changeCloudPassword'
);
}
if (this.hasCloudProject()) {
menu.addLine();
menu.addItem(
'Open in Community Site',
() => {
var dict = this.urlParameters();
window.open(
this.cloud.showProjectPath(
dict.Username, dict.ProjectName
),
'_blank'
);
}
);
}
if (shiftClicked) {
menu.addLine();
menu.addItem(
'export project media only...',
() => {
if (this.projectName) {
this.exportProjectMedia(this.projectName);
} else {
this.prompt(
'Export Project As...',
name => this.exportProjectMedia(name),
null,
'exportProject'
);
}
},
null,
this.hasChangedMedia ? new Color(100, 0, 0) : new Color(0, 100, 0)
);
menu.addItem(
'export project without media...',
() => {
if (this.projectName) {
this.exportProjectNoMedia(this.projectName);
} else {
this.prompt(
'Export Project As...',
name => this.exportProjectNoMedia(name),
null,
'exportProject'
);
}
},
null,
new Color(100, 0, 0)
);
menu.addItem(
'export project as cloud data...',
() => {
if (this.projectName) {
this.exportProjectAsCloudData(this.projectName);
} else {
this.prompt(
'Export Project As...',
name => this.exportProjectAsCloudData(name),
null,
'exportProject'
);
}
},
null,
new Color(100, 0, 0)
);
menu.addLine();
menu.addItem(
'open shared project from cloud...',
() => {
this.prompt(
'Author name…',
usr => {
this.prompt(
'Project name...',
prj => {
this.showMessage(
'Fetching project\nfrom the cloud...'
);
this.cloud.getPublicProject(
prj,
usr.toLowerCase(),
projectData => {
var msg;
if (
!Process.prototype.isCatchingErrors
) {
window.open(
'data:text/xml,' + projectData
);
}
this.nextSteps([
() => {
msg = this.showMessage(
'Opening project...'
);
},
() => {
this.rawOpenCloudDataString(
projectData
);
msg.destroy();
},
]);
},
this.cloudError()
);
},
null,
'project'
);
},
null,
'project'
);
},
null,
new Color(100, 0, 0)
);
}
menu.popup(world, pos);
};
IDE_Morph.prototype.settingsMenu = function () {
var menu,
stage = this.stage,
world = this.world(),
pos = this.controlBar.settingsButton.bottomLeft(),
shiftClicked = (world.currentKey === 16);
function addPreference(label, toggle, test, onHint, offHint, hide) {
var on = '\u2611 ',
off = '\u2610 ';
if (!hide || shiftClicked) {
menu.addItem(
(test ? on : off) + localize(label),
toggle,
test ? onHint : offHint,
hide ? new Color(100, 0, 0) : null
);
}
}
menu = new MenuMorph(this);
menu.addPair(
[
new SymbolMorph(
'globe',
MorphicPreferences.menuFontSize
),
localize('Language...')
],
'languageMenu'
);
menu.addItem(
'Zoom blocks...',
'userSetBlocksScale'
);
menu.addItem(
'Stage size...',
'userSetStageSize'
);
if (shiftClicked) {
menu.addItem(
'Dragging threshold...',
'userSetDragThreshold',
'specify the distance the hand has to move\n' +
'before it picks up an object',
new Color(100, 0, 0)
);
}
menu.addItem(
'Microphone resolution...',
'microphoneMenu'
);
menu.addLine();
/*
addPreference(
'JavaScript',
() => {
Process.prototype.enableJS = !Process.prototype.enableJS;
this.currentSprite.blocksCache.operators = null;
this.currentSprite.paletteCache.operators = null;
this.refreshPalette();
},
Process.prototype.enableJS,
'uncheck to disable support for\nnative JavaScript functions',
'check to support\nnative JavaScript functions'
);
*/
if (isRetinaSupported()) {
addPreference(
'Retina display support',
'toggleRetina',
isRetinaEnabled(),
'uncheck for lower resolution,\nsaves computing resources',
'check for higher resolution,\nuses more computing resources',
true
);
}
addPreference(
'Input sliders',
'toggleInputSliders',
MorphicPreferences.useSliderForInput,
'uncheck to disable\ninput sliders for\nentry fields',
'check to enable\ninput sliders for\nentry fields'
);
if (MorphicPreferences.useSliderForInput) {
addPreference(
'Execute on slider change',
'toggleSliderExecute',
ArgMorph.prototype.executeOnSliderEdit,
'uncheck to suppress\nrunning scripts\nwhen moving the slider',
'check to run\nthe edited script\nwhen moving the slider'
);
}
addPreference(
'Turbo mode',
'toggleFastTracking',
this.stage.isFastTracked,
'uncheck to run scripts\nat normal speed',
'check to prioritize\nscript execution'
);
addPreference(
'Visible stepping',
'toggleSingleStepping',
Process.prototype.enableSingleStepping,
'uncheck to turn off\nvisible stepping',
'check to turn on\n visible stepping (slow)',
false
);
addPreference(
'Log pen vectors',
() => StageMorph.prototype.enablePenLogging =
!StageMorph.prototype.enablePenLogging,
StageMorph.prototype.enablePenLogging,
'uncheck to turn off\nlogging pen vectors',
'check to turn on\nlogging pen vectors',
false
);
addPreference(
'Ternary Boolean slots',
() => BooleanSlotMorph.prototype.isTernary =
!BooleanSlotMorph.prototype.isTernary,
BooleanSlotMorph.prototype.isTernary,
'uncheck to limit\nBoolean slots to true / false',
'check to allow\nempty Boolean slots',
true
);
addPreference(
'Camera support',
'toggleCameraSupport',
CamSnapshotDialogMorph.prototype.enableCamera,
'uncheck to disable\ncamera support',
'check to enable\ncamera support',
true
);
menu.addLine(); // everything visible below is persistent
addPreference(
'Blurred shadows',
'toggleBlurredShadows',
useBlurredShadows,
'uncheck to use solid drop\nshadows and highlights',
'check to use blurred drop\nshadows and highlights',
true
);
addPreference(
'Zebra coloring',
'toggleZebraColoring',
BlockMorph.prototype.zebraContrast,
'uncheck to disable alternating\ncolors for nested block',
'check to enable alternating\ncolors for nested blocks',
true
);
addPreference(
'Dynamic input labels',
'toggleDynamicInputLabels',
SyntaxElementMorph.prototype.dynamicInputLabels,
'uncheck to disable dynamic\nlabels for variadic inputs',
'check to enable dynamic\nlabels for variadic inputs',
true
);
addPreference(
'Prefer empty slot drops',
'togglePreferEmptySlotDrops',
ScriptsMorph.prototype.isPreferringEmptySlots,
'uncheck to allow dropped\nreporters to kick out others',
'settings menu prefer empty slots hint',
true
);
addPreference(
'Long form input dialog',
'toggleLongFormInputDialog',
InputSlotDialogMorph.prototype.isLaunchingExpanded,
'uncheck to use the input\ndialog in short form',
'check to always show slot\ntypes in the input dialog'
);
addPreference(
'Plain prototype labels',
'togglePlainPrototypeLabels',
BlockLabelPlaceHolderMorph.prototype.plainLabel,
'uncheck to always show (+) symbols\nin block prototype labels',
'check to hide (+) symbols\nin block prototype labels'
);
addPreference(
'Virtual keyboard',
'toggleVirtualKeyboard',
MorphicPreferences.useVirtualKeyboard,
'uncheck to disable\nvirtual keyboard support\nfor mobile devices',
'check to enable\nvirtual keyboard support\nfor mobile devices',
true
);
addPreference(
'Clicking sound',
() => {
BlockMorph.prototype.toggleSnapSound();
if (BlockMorph.prototype.snapSound) {
this.saveSetting('click', true);
} else {
this.removeSetting('click');
}
},
BlockMorph.prototype.snapSound,
'uncheck to turn\nblock clicking\nsound off',
'check to turn\nblock clicking\nsound on'
);
addPreference(
'Animations',
() => this.isAnimating = !this.isAnimating,
this.isAnimating,
'uncheck to disable\nIDE animations',
'check to enable\nIDE animations',
true
);
addPreference(
'Cache Inputs',
() => {
BlockMorph.prototype.isCachingInputs =
!BlockMorph.prototype.isCachingInputs;
},
BlockMorph.prototype.isCachingInputs,
'uncheck to stop caching\ninputs (for debugging the evaluator)',
'check to cache inputs\nboosts recursion',
true
);
addPreference(
'Rasterize SVGs',
() => MorphicPreferences.rasterizeSVGs =
!MorphicPreferences.rasterizeSVGs,
MorphicPreferences.rasterizeSVGs,
'uncheck for smooth\nscaling of vector costumes',
'check to rasterize\nSVGs on import',
true
);
addPreference(
'Flat design',
() => {
if (MorphicPreferences.isFlat) {
return this.defaultDesign();
}
this.flatDesign();
},
MorphicPreferences.isFlat,
'uncheck for default\nGUI design',
'check for alternative\nGUI design',
false
);
addPreference(
'Nested auto-wrapping',
() => {
ScriptsMorph.prototype.enableNestedAutoWrapping =
!ScriptsMorph.prototype.enableNestedAutoWrapping;
if (ScriptsMorph.prototype.enableNestedAutoWrapping) {
this.removeSetting('autowrapping');
} else {
this.saveSetting('autowrapping', false);
}
},
ScriptsMorph.prototype.enableNestedAutoWrapping,
'uncheck to confine auto-wrapping\nto top-level block stacks',
'check to enable auto-wrapping\ninside nested block stacks',
true
);
addPreference(
'Project URLs',
() => {
this.projectsInURLs = !this.projectsInURLs;
if (this.projectsInURLs) {
this.saveSetting('longurls', true);
} else {
this.removeSetting('longurls');
}
},
this.projectsInURLs,
'uncheck to disable\nproject data in URLs',
'check to enable\nproject data in URLs',
true
);
addPreference(
'Sprite Nesting',
() => SpriteMorph.prototype.enableNesting =
!SpriteMorph.prototype.enableNesting,
SpriteMorph.prototype.enableNesting,
'uncheck to disable\nsprite composition',
'check to enable\nsprite composition',
true
);
addPreference(
'First-Class Sprites',
() => {
SpriteMorph.prototype.enableFirstClass =
!SpriteMorph.prototype.enableFirstClass;
this.currentSprite.blocksCache.sensing = null;
this.currentSprite.paletteCache.sensing = null;
this.refreshPalette();
},
SpriteMorph.prototype.enableFirstClass,
'uncheck to disable support\nfor first-class sprites',
'check to enable support\n for first-class sprite',
true
);
addPreference(
'Keyboard Editing',
() => {
ScriptsMorph.prototype.enableKeyboard =
!ScriptsMorph.prototype.enableKeyboard;
this.currentSprite.scripts.updateToolbar();
if (ScriptsMorph.prototype.enableKeyboard) {
this.removeSetting('keyboard');
} else {
this.saveSetting('keyboard', false);
}
},
ScriptsMorph.prototype.enableKeyboard,
'uncheck to disable\nkeyboard editing support',
'check to enable\nkeyboard editing support',
true
);
addPreference(
'Table support',
() => {
List.prototype.enableTables =
!List.prototype.enableTables;
if (List.prototype.enableTables) {
this.removeSetting('tables');
} else {
this.saveSetting('tables', false);
}
},
List.prototype.enableTables,
'uncheck to disable\nmulti-column list views',
'check for multi-column\nlist view support',
true
);
if (List.prototype.enableTables) {
addPreference(
'Table lines',
() => {
TableMorph.prototype.highContrast =
!TableMorph.prototype.highContrast;
if (TableMorph.prototype.highContrast) {
this.saveSetting('tableLines', true);
} else {
this.removeSetting('tableLines');
}
},
TableMorph.prototype.highContrast,
'uncheck for less contrast\nmulti-column list views',
'check for higher contrast\ntable views',
true
);
}
addPreference(
'Live coding support',
() => Process.prototype.enableLiveCoding =
!Process.prototype.enableLiveCoding,
Process.prototype.enableLiveCoding,
'EXPERIMENTAL! uncheck to disable live\ncustom control structures',
'EXPERIMENTAL! check to enable\n live custom control structures',
true
);
addPreference(
'JIT compiler support',
() => {
Process.prototype.enableCompiling =
!Process.prototype.enableCompiling;
this.currentSprite.blocksCache.operators = null;
this.currentSprite.paletteCache.operators = null;
this.refreshPalette();
},
Process.prototype.enableCompiling,
'EXPERIMENTAL! uncheck to disable live\nsupport for compiling',
'EXPERIMENTAL! check to enable\nsupport for compiling',
true
);
menu.addLine(); // everything below this line is stored in the project
addPreference(
'Thread safe scripts',
() => stage.isThreadSafe = !stage.isThreadSafe,
this.stage.isThreadSafe,
'uncheck to allow\nscript reentrance',
'check to disallow\nscript reentrance'
);
addPreference(
'Prefer smooth animations',
'toggleVariableFrameRate',
StageMorph.prototype.frameRate,
'uncheck for greater speed\nat variable frame rates',
'check for smooth, predictable\nanimations across computers',
true
);
addPreference(
'Flat line ends',
() => SpriteMorph.prototype.useFlatLineEnds =
!SpriteMorph.prototype.useFlatLineEnds,
SpriteMorph.prototype.useFlatLineEnds,
'uncheck for round ends of lines',
'check for flat ends of lines'
);
addPreference(
'Codification support',
() => {
StageMorph.prototype.enableCodeMapping =
!StageMorph.prototype.enableCodeMapping;
this.currentSprite.blocksCache.variables = null;
this.currentSprite.paletteCache.variables = null;
this.refreshPalette();
},
StageMorph.prototype.enableCodeMapping,
'uncheck to disable\nblock to text mapping features',
'check for block\nto text mapping features',
false
);
addPreference(
'Inheritance support',
() => {
StageMorph.prototype.enableInheritance =
!StageMorph.prototype.enableInheritance;
this.currentSprite.blocksCache.variables = null;
this.currentSprite.paletteCache.variables = null;
this.refreshPalette();
},
StageMorph.prototype.enableInheritance,
'uncheck to disable\nsprite inheritance features',
'check for sprite\ninheritance features',
true
);
addPreference(
'Hyper blocks support',
() => Process.prototype.enableHyperOps =
!Process.prototype.enableHyperOps,
Process.prototype.enableHyperOps,
'uncheck to disable\nusing operators on lists and tables',
'check to enable\nusing operators on lists and tables',
true
);
addPreference(
'Persist linked sublist IDs',
() => StageMorph.prototype.enableSublistIDs =
!StageMorph.prototype.enableSublistIDs,
StageMorph.prototype.enableSublistIDs,
'uncheck to disable\nsaving linked sublist identities',
'check to enable\nsaving linked sublist identities',
true
);
addPreference(
'Enable command drops in all rings',
() => RingReporterSlotMorph.prototype.enableCommandDrops =
!RingReporterSlotMorph.prototype.enableCommandDrops,
RingReporterSlotMorph.prototype.enableCommandDrops,
'uncheck to disable\ndropping commands in reporter rings',
'check to enable\ndropping commands in all rings',
true
);
menu.popup(world, pos);
};
IDE_Morph.prototype.projectMenu = function () {
var menu,
world = this.world(),
pos = this.controlBar.projectButton.bottomLeft(),
graphicsName = this.currentSprite instanceof SpriteMorph ?
'Costumes' : 'Backgrounds',
shiftClicked = (world.currentKey === 16);
menu = new MenuMorph(this);
menu.addItem('Project notes...', 'editProjectNotes');
menu.addLine();
menu.addPair('New', 'createNewProject', '^N');
menu.addPair('Open...', 'openProjectsBrowser', '^O');
menu.addPair('Save', "save", '^S');
menu.addItem('Save As...', 'saveProjectsBrowser');
menu.addLine();
menu.addItem(
'Import...',
'importLocalFile',
'file menu import hint' // looks up the actual text in the translator
);
if (shiftClicked) {
menu.addItem(
localize(
'Export project...') + ' ' + localize('(in a new window)'
),
() => {
if (this.projectName) {
this.exportProject(this.projectName, shiftClicked);
} else {
this.prompt(
'Export Project As...',
// false - override the shiftClick setting to use XML:
name => this.exportProject(name, false),
null,
'exportProject'
);
}
},
'show project data as XML\nin a new browser window',
new Color(100, 0, 0)
);
}
menu.addItem(
shiftClicked ?
'Export project as plain text...' : 'Export project...',
() => {
if (this.projectName) {
this.exportProject(this.projectName, shiftClicked);
} else {
this.prompt(
'Export Project As...',
name => this.exportProject(name, shiftClicked),
null,
'exportProject'
);
}
},
'save project data as XML\nto your downloads folder',
shiftClicked ? new Color(100, 0, 0) : null
);
if (this.stage.globalBlocks.length) {
menu.addItem(
'Export blocks...',
() => this.exportGlobalBlocks(),
'show global custom block definitions as XML' +
'\nin a new browser window'
);
menu.addItem(
'Unused blocks...',
() => this.removeUnusedBlocks(),
'find unused global custom blocks' +
'\nand remove their definitions'
);
}
menu.addItem(
'Export summary...',
() => this.exportProjectSummary(),
'open a new browser browser window\n with a summary of this project'
);
if (shiftClicked) {
menu.addItem(
'Export summary with drop-shadows...',
() => this.exportProjectSummary(true),
'open a new browser browser window' +
'\nwith a summary of this project' +
'\nwith drop-shadows on all pictures.' +
'\nnot supported by all browsers',
new Color(100, 0, 0)
);
menu.addItem(
'Export all scripts as pic...',
() => this.exportScriptsPicture(),
'show a picture of all scripts\nand block definitions',
new Color(100, 0, 0)
);
}
menu.addLine();
menu.addItem(
'Libraries...',
() => {
if (location.protocol === 'file:') {
this.importLocalFile();
return;
}
this.getURL(
this.resourceURL('libraries', 'LIBRARIES'),
txt => {
var libraries = this.parseResourceFile(txt);
new LibraryImportDialogMorph(this, libraries).popUp();
}
);
},
'Select categories of additional blocks to add to this project.'
);
menu.addItem(
localize(graphicsName) + '...',
() => {
if (location.protocol === 'file:') {
this.importLocalFile();
return;
}
this.importMedia(graphicsName);
},
'Select a costume from the media library'
);
menu.addItem(
localize('Sounds') + '...',
() => {
if (location.protocol === 'file:') {
this.importLocalFile();
return;
}
this.importMedia('Sounds');
},
'Select a sound from the media library'
);
menu.popup(world, pos);
};
IDE_Morph.prototype.resourceURL = function () {
// Take in variadic inputs that represent an a nested folder structure.
// Method can be easily overridden if running in a custom location.
// Default Snap! simply returns a path (relative to snap.html)
var args = Array.prototype.slice.call(arguments, 0);
return args.join('/');
};
IDE_Morph.prototype.getMediaList = function (dirname, callback) {
// Invoke the given callback with a list of files in a directory
// based on the contents file.
// If no callback is specified, synchronously return the list of files
// Note: Synchronous fetching has been deprecated and should be switched
var url = this.resourceURL(dirname, dirname.toUpperCase()),
async = callback instanceof Function,
data;
function alphabetically(x, y) {
return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1;
}
if (async) {
this.getURL(
url,
txt => {
var data = this.parseResourceFile(txt);
data.sort(alphabetically);
callback.call(this, data);
}
);
} else {
data = this.parseResourceFile(this.getURL(url));
data.sort(alphabetically);
return data;
}
};
IDE_Morph.prototype.parseResourceFile = function (text) {
// A Resource File lists all the files that could be loaded in a submenu
// Examples are libraries/LIBRARIES, Costumes/COSTUMES, etc
// The file format is tab-delimited, with unix newlines:
// file-name, Display Name, Help Text (optional)
var parts,
items = [];
text.split('\n').map(line =>
line.trim()
).filter(line =>
line.length > 0
).forEach(line => {
parts = line.split('\t').map(str => str.trim());
if (parts.length < 2) {return; }
items.push({
fileName: parts[0],
name: parts[1],
description: parts.length > 2 ? parts[2] : ''
});
});
return items;
};
IDE_Morph.prototype.importLocalFile = function () {
var inp = document.createElement('input'),
world = this.world();
if (this.filePicker) {
document.body.removeChild(this.filePicker);
this.filePicker = null;
}
inp.type = 'file';
inp.style.color = "transparent";
inp.style.backgroundColor = "transparent";
inp.style.border = "none";
inp.style.outline = "none";
inp.style.position = "absolute";
inp.style.top = "0px";
inp.style.left = "0px";
inp.style.width = "0px";
inp.style.height = "0px";
inp.style.display = "none";
inp.addEventListener(
"change",
() => {
document.body.removeChild(inp);
this.filePicker = null;
world.hand.processDrop(inp.files);
},
false
);
document.body.appendChild(inp);
this.filePicker = inp;
inp.click();
};
IDE_Morph.prototype.importMedia = function (folderName) {
// open a dialog box letting the user browse available "built-in"
// costumes, backgrounds or sounds
var msg = this.showMessage('Opening ' + folderName + '...');
this.getMediaList(
folderName,
items => {
msg.destroy();
this.popupMediaImportDialog(folderName, items);
}
);
};
IDE_Morph.prototype.popupMediaImportDialog = function (folderName, items) {
// private - this gets called by importMedia() and creates
// the actual dialog
var dialog = new DialogBoxMorph().withKey('import' + folderName),
frame = new ScrollFrameMorph(),
selectedIcon = null,
turtle = new SymbolMorph('turtle', 60),
myself = this,
world = this.world(),
handle;
frame.acceptsDrops = false;
frame.contents.acceptsDrops = false;
frame.color = myself.groupColor;
frame.fixLayout = nop;
dialog.labelString = folderName;
dialog.createLabel();
dialog.addBody(frame);
dialog.addButton('ok', 'Import');
dialog.addButton('cancel', 'Cancel');
dialog.ok = function () {
if (selectedIcon) {
if (selectedIcon.object instanceof Sound) {
myself.droppedAudio(
selectedIcon.object.copy().audio,
selectedIcon.labelString
);
} else if (selectedIcon.object instanceof SVG_Costume) {
myself.droppedSVG(
selectedIcon.object.contents,
selectedIcon.labelString
);
} else {
myself.droppedImage(
selectedIcon.object.contents,
selectedIcon.labelString
);
}
}
};
dialog.fixLayout = function () {
var th = fontHeight(this.titleFontSize) + this.titlePadding * 2,
x = 0,
y = 0,
fp, fw;
this.buttons.fixLayout();
this.body.setPosition(this.position().add(new Point(
this.padding,
th + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height() - this.padding * 3 - th - this.buttons.height()
));
fp = this.body.position();
fw = this.body.width();
frame.contents.children.forEach(function (icon) {
icon.setPosition(fp.add(new Point(x, y)));
x += icon.width();
if (x + icon.width() > fw) {
x = 0;
y += icon.height();
}
});
frame.contents.adjustBounds();
this.label.setCenter(this.center());
this.label.setTop(this.top() + (th - this.label.height()) / 2);
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
};
items.forEach(item => {
// Caution: creating very many thumbnails can take a long time!
var url = this.resourceURL(folderName, item.fileName),
img = new Image(),
suffix = url.slice(url.lastIndexOf('.') + 1).toLowerCase(),
isSVG = suffix === 'svg' && !MorphicPreferences.rasterizeSVGs,
isSound = contains(['wav', 'mp3'], suffix),
icon;
if (isSound) {
icon = new SoundIconMorph(new Sound(new Audio(), item.name));
} else {
icon = new CostumeIconMorph(
new Costume(turtle.getImage(), item.name)
);
}
icon.isDraggable = false;
icon.userMenu = nop;
icon.action = function () {
if (selectedIcon === icon) {return; }
var prevSelected = selectedIcon;
selectedIcon = icon;
if (prevSelected) {prevSelected.refresh(); }
};
icon.doubleClickAction = dialog.ok;
icon.query = function () {
return icon === selectedIcon;
};
frame.addContents(icon);
if (isSound) {
icon.object.audio.onloadeddata = function () {
icon.createThumbnail();
icon.fixLayout();
icon.refresh();
};
icon.object.audio.src = url;
icon.object.audio.load();
} else if (isSVG) {
img.onload = function () {
icon.object = new SVG_Costume(img, item.name);
icon.refresh();
};
this.getURL(
url,
txt => img.src = 'data:image/svg+xml;base64,' +
window.btoa(txt)
);
} else {
img.onload = function () {
var canvas = newCanvas(new Point(img.width, img.height), true);
canvas.getContext('2d').drawImage(img, 0, 0);
icon.object = new Costume(canvas, item.name);
icon.refresh();
};
img.src = url;
}
});
dialog.popUp(world);
dialog.setExtent(new Point(400, 300));
dialog.setCenter(world.center());
handle = new HandleMorph(
dialog,
300,
280,
dialog.corner,
dialog.corner
);
};
// IDE_Morph menu actions
IDE_Morph.prototype.aboutSnap = function () {
var dlg, aboutTxt, noticeTxt, creditsTxt, versions = '', translations,
module, btn1, btn2, btn3, btn4, licenseBtn, translatorsBtn,
world = this.world();
aboutTxt = 'Snap! 6.0.0 - dev -\nBuild Your Own Blocks\n\n'
+ 'Copyright \u24B8 2008-2020 Jens M\u00F6nig and '
+ 'Brian Harvey\n'
+ '[email protected], [email protected]\n\n'
+ 'Snap! is developed by the University of California, Berkeley\n'
+ ' with support from the National Science Foundation (NSF), '
+ 'MioSoft, \n'
+ 'the Communications Design Group (CDG) at SAP Labs, and the\n'
+ 'Human Advancement Research Community (HARC) at YC Research.\n'
+ 'The design of Snap! is influenced and inspired by Scratch,\n'
+ 'from the Lifelong Kindergarten group at the MIT Media Lab\n\n'
+ 'for more information see https://snap.berkeley.edu\n'
+ 'and http://scratch.mit.edu';
noticeTxt = localize('License')
+ '\n\n'
+ 'Snap! is free software: you can redistribute it and/or modify\n'
+ 'it under the terms of the GNU Affero General Public License as\n'
+ 'published by the Free Software Foundation, either version 3 of\n'
+ 'the License, or (at your option) any later version.\n\n'
+ 'This program is distributed in the hope that it will be useful,\n'
+ 'but WITHOUT ANY WARRANTY; without even the implied warranty of\n'
+ 'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n'
+ 'GNU Affero General Public License for more details.\n\n'
+ 'You should have received a copy of the\n'
+ 'GNU Affero General Public License along with this program.\n'
+ 'If not, see http://www.gnu.org/licenses/\n\n'
+ 'Want to use Snap! but scared by the open-source license?\n'
+ 'Get in touch with us, we\'ll make it work.';
creditsTxt = localize('Contributors')
+ '\n\nNathan Dinsmore: Saving/Loading, Snap-Logo Design, '
+ '\ncountless bugfixes and optimizations'
+ '\nMichael Ball: Time/Date UI, Library Import Dialog,'
+ '\ncountless bugfixes and optimizations'
+ '\nBernat Romagosa: Countless contributions'
+ '\nBartosz Leper: Retina Display Support'
+ '\nZhenlei Jia and Dariusz Dorożalski: IME text editing'
+ '\nKen Kahn: IME support and countless other contributions'
+ '\nJosep Ferràndiz: Video Motion Detection'
+ '\nJoan Guillén: Countless contributions'
+ '\nKartik Chandra: Paint Editor'
+ '\nCarles Paredes: Initial Vector Paint Editor'
+ '\n"Ava" Yuan Yuan, Dylan Servilla: Graphic Effects'
+ '\nKyle Hotchkiss: Block search design'
+ '\nBrian Broll: Many bugfixes and optimizations'
+ '\nIan Reynolds: UI Design, Event Bindings, '
+ 'Sound primitives'
+ '\nIvan Motyashov: Initial Squeak Porting'
+ '\nLucas Karahadian: Piano Keyboard Design'
+ '\nDavide Della Casa: Morphic Optimizations'
+ '\nAchal Dave: Web Audio'
+ '\nJoe Otto: Morphic Testing and Debugging';
for (module in modules) {
if (Object.prototype.hasOwnProperty.call(modules, module)) {
versions += ('\n' + module + ' (' +
modules[module] + ')');
}
}
if (versions !== '') {
versions = localize('current module versions:') + ' \n\n' +
'morphic (' + morphicVersion + ')' +
versions;
}
translations = localize('Translations') + '\n' + SnapTranslator.credits();
dlg = new DialogBoxMorph();
dlg.inform('About Snap', aboutTxt, world);
btn1 = dlg.buttons.children[0];
translatorsBtn = dlg.addButton(
() => {
dlg.body.text = translations;
dlg.body.fixLayout();
btn1.show();
btn2.show();
btn3.hide();
btn4.hide();
licenseBtn.hide();
translatorsBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'Translators...'
);
btn2 = dlg.addButton(
() => {
dlg.body.text = aboutTxt;
dlg.body.fixLayout();
btn1.show();
btn2.hide();
btn3.show();
btn4.show();
licenseBtn.show();
translatorsBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'Back...'
);
btn2.hide();
licenseBtn = dlg.addButton(
() => {
dlg.body.text = noticeTxt;
dlg.body.fixLayout();
btn1.show();
btn2.show();
btn3.hide();
btn4.hide();
licenseBtn.hide();
translatorsBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'License...'
);
btn3 = dlg.addButton(
() => {
dlg.body.text = versions;
dlg.body.fixLayout();
btn1.show();
btn2.show();
btn3.hide();
btn4.hide();
licenseBtn.hide();
translatorsBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'Modules...'
);
btn4 = dlg.addButton(
() => {
dlg.body.text = creditsTxt;
dlg.body.fixLayout();
btn1.show();
btn2.show();
translatorsBtn.show();
btn3.hide();
btn4.hide();
licenseBtn.hide();
dlg.fixLayout();
dlg.setCenter(world.center());
},
'Credits...'
);
translatorsBtn.hide();
dlg.fixLayout();
};
IDE_Morph.prototype.editProjectNotes = function () {
var dialog = new DialogBoxMorph().withKey('projectNotes'),
frame = new ScrollFrameMorph(),
text = new TextMorph(this.projectNotes || ''),
size = 250,
world = this.world();
frame.padding = 6;
frame.setWidth(size);
frame.acceptsDrops = false;
frame.contents.acceptsDrops = false;
text.setWidth(size - frame.padding * 2);
text.setPosition(frame.topLeft().add(frame.padding));
text.enableSelecting();
text.isEditable = true;
frame.setHeight(size);
frame.fixLayout = nop;
frame.edge = InputFieldMorph.prototype.edge;
frame.fontSize = InputFieldMorph.prototype.fontSize;
frame.typeInPadding = InputFieldMorph.prototype.typeInPadding;
frame.contrast = InputFieldMorph.prototype.contrast;
frame.render = InputFieldMorph.prototype.render;
frame.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
frame.addContents(text);
dialog.getInput = () => text.text;
dialog.target = this;
dialog.action = (note) => this.projectNotes = note;
dialog.justDropped = () => text.edit();
dialog.labelString = 'Project Notes';
dialog.createLabel();
dialog.addBody(frame);
dialog.addButton('ok', 'OK');
dialog.addButton('cancel', 'Cancel');
dialog.fixLayout();
dialog.popUp(world);
dialog.setCenter(world.center());
text.edit();
};
IDE_Morph.prototype.newProject = function () {
this.source = this.cloud.username ? 'cloud' : null;
if (this.stage) {
this.stage.destroy();
}
if (location.hash.substr(0, 6) !== '#lang:') {
location.hash = '';
}
this.globalVariables = new VariableFrame();
this.currentSprite = new SpriteMorph(this.globalVariables);
this.sprites = new List([this.currentSprite]);
StageMorph.prototype.dimensions = new Point(480, 360);
StageMorph.prototype.hiddenPrimitives = {};
StageMorph.prototype.codeMappings = {};
StageMorph.prototype.codeHeaders = {};
StageMorph.prototype.enableCodeMapping = false;
StageMorph.prototype.enableInheritance = true;
StageMorph.prototype.enableSublistIDs = false;
StageMorph.prototype.enablePenLogging = false;
SpriteMorph.prototype.useFlatLineEnds = false;
Process.prototype.enableLiveCoding = false;
Process.prototype.enableHyperOps = true;
this.setProjectName('');
this.projectNotes = '';
this.createStage();
this.add(this.stage);
this.createCorral();
this.selectSprite(this.stage.children[0]);
this.fixLayout();
};
IDE_Morph.prototype.save = function () {
// temporary hack - only allow exporting projects to disk
// when running Snap! locally without a web server
if (location.protocol === 'file:') {
if (this.projectName) {
this.exportProject(this.projectName, false);
} else {
this.prompt(
'Export Project As...',
name => this.exportProject(name, false),
null,
'exportProject'
);
}
return;
}
if (this.source === 'examples' || this.source === 'local') {
// cannot save to examples, deprecated localStorage
this.source = null;
}
if (this.projectName) {
if (this.source === 'disk') {
this.exportProject(this.projectName);
} else if (this.source === 'cloud') {
this.saveProjectToCloud(this.projectName);
} else {
this.saveProjectsBrowser();
}
} else {
this.saveProjectsBrowser();
}
};
IDE_Morph.prototype.exportProject = function (name, plain) {
// Export project XML, saving a file to disk
// newWindow requests displaying the project in a new tab.
var menu, str, dataPrefix;
if (name) {
this.setProjectName(name);
dataPrefix = 'data:text/' + plain ? 'plain,' : 'xml,';
try {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
this.setURL('#open:' + dataPrefix + encodeURIComponent(str));
this.saveXMLAs(str, name);
menu.destroy();
this.showMessage('Exported!', 1);
} catch (err) {
if (Process.prototype.isCatchingErrors) {
this.showMessage('Export failed: ' + err);
} else {
throw err;
}
}
}
};
IDE_Morph.prototype.exportGlobalBlocks = function () {
if (this.stage.globalBlocks.length > 0) {
new BlockExportDialogMorph(
this.serializer,
this.stage.globalBlocks
).popUp(this.world());
} else {
this.inform(
'Export blocks',
'this project doesn\'t have any\n'
+ 'custom global blocks yet'
);
}
};
IDE_Morph.prototype.removeUnusedBlocks = function () {
var targets = this.sprites.asArray().concat([this.stage]),
globalBlocks = this.stage.globalBlocks,
unused = [],
isDone = false,
found;
function scan() {
return globalBlocks.filter(def => {
if (contains(unused, def)) {return false; }
return targets.every((each, trgIdx) =>
!each.usesBlockInstance(def, true, trgIdx, unused)
);
});
}
while (!isDone) {
found = scan();
if (found.length) {
unused = unused.concat(found);
} else {
isDone = true;
}
}
if (unused.length > 0) {
new BlockRemovalDialogMorph(
unused,
this.stage
).popUp(this.world());
} else {
this.inform(
'Remove unused blocks',
'there are currently no unused\n'
+ 'global custom blocks in this project'
);
}
};
IDE_Morph.prototype.exportSprite = function (sprite) {
var str = this.serializer.serialize(sprite.allParts());
str = '<sprites app="'
+ this.serializer.app
+ '" version="'
+ this.serializer.version
+ '">'
+ str
+ '</sprites>';
this.saveXMLAs(str, sprite.name);
};
IDE_Morph.prototype.exportScriptsPicture = function () {
var pics = [],
pic,
padding = 20,
w = 0,
h = 0,
y = 0,
ctx;
// collect all script pics
this.sprites.asArray().forEach(sprite => {
pics.push(sprite.getImage());
pics.push(sprite.scripts.scriptsPicture());
sprite.customBlocks.forEach(def =>
pics.push(def.scriptsPicture())
);
});
pics.push(this.stage.getImage());
pics.push(this.stage.scripts.scriptsPicture());
this.stage.customBlocks.forEach(def =>
pics.push(def.scriptsPicture())
);
// collect global block pics
this.stage.globalBlocks.forEach(def =>
pics.push(def.scriptsPicture())
);
pics = pics.filter(each => !isNil(each));
// determine dimensions of composite
pics.forEach(each => {
w = Math.max(w, each.width);
h += (each.height);
h += padding;
});
h -= padding;
pic = newCanvas(new Point(w, h));
ctx = pic.getContext('2d');
// draw all parts
pics.forEach(each => {
ctx.drawImage(each, 0, y);
y += padding;
y += each.height;
});
this.saveCanvasAs(pic, this.projectName || localize('Untitled'));
};
IDE_Morph.prototype.exportProjectSummary = function (useDropShadows) {
var html, head, meta, css, body, pname, notes, toc, globalVars,
stage = this.stage;
function addNode(tag, node, contents) {
if (!node) {node = body; }
return new XML_Element(tag, contents, node);
}
function add(contents, tag, node) {
if (!tag) {tag = 'p'; }
if (!node) {node = body; }
return new XML_Element(tag, contents, node);
}
function addImage(canvas, node, inline) {
if (!node) {node = body; }
var para = !inline ? addNode('p', node) : null,
pic = addNode('img', para || node);
pic.attributes.src = canvas.toDataURL();
return pic;
}
function addVariables(varFrame) {
var names = varFrame.names().sort(),
isFirst = true,
ul;
if (names.length) {
add(localize('Variables'), 'h3');
names.forEach(name => {
/*
addImage(
SpriteMorph.prototype.variableBlock(name).scriptPic()
);
*/
var watcher, listMorph, li, img;
if (isFirst) {
ul = addNode('ul');
isFirst = false;
}
li = addNode('li', ul);
watcher = new WatcherMorph(
name,
SpriteMorph.prototype.blockColor.variables,
varFrame,
name
);
listMorph = watcher.cellMorph.contentsMorph;
if (listMorph instanceof ListWatcherMorph) {
listMorph.expand();
}
img = addImage(watcher.fullImage(), li);
img.attributes.class = 'script';
});
}
}
function addBlocks(definitions) {
if (definitions.length) {
add(localize('Blocks'), 'h3');
SpriteMorph.prototype.categories.forEach(category => {
var isFirst = true,
ul;
definitions.forEach(def => {
var li, blockImg;
if (def.category === category) {
if (isFirst) {
add(
localize(
category[0].toUpperCase().concat(
category.slice(1)
)
),
'h4'
);
ul = addNode('ul');
isFirst = false;
}
li = addNode('li', ul);
blockImg = addImage(
def.templateInstance().scriptPic(),
li
);
blockImg.attributes.class = 'script';
def.sortedElements().forEach(script => {
var defImg = addImage(
script instanceof BlockMorph ?
script.scriptPic()
: script.fullImage(),
li
);
defImg.attributes.class = 'script';
});
}
});
});
}
}
pname = this.projectName || localize('untitled');
html = new XML_Element('html');
html.attributes.lang = SnapTranslator.language;
// html.attributes.contenteditable = 'true';
head = addNode('head', html);
meta = addNode('meta', head);
meta.attributes.charset = 'UTF-8';
if (useDropShadows) {
css = 'img {' +
'vertical-align: top;' +
'filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.5));' +
'-webkit-filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.5));' +
'-ms-filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.5));' +
'}' +
'.toc {' +
'vertical-align: middle;' +
'padding: 2px 1em 2px 1em;' +
'}';
} else {
css = 'img {' +
'vertical-align: top;' +
'}' +
'.toc {' +
'vertical-align: middle;' +
'padding: 2px 1em 2px 1em;' +
'}' +
'.sprite {' +
'border: 1px solid lightgray;' +
'}';
}
addNode('style', head, css);
add(pname, 'title', head);
body = addNode('body', html);
add(pname, 'h1');
/*
if (this.cloud.username) {
add(localize('by ') + this.cloud.username);
}
*/
if (location.hash.indexOf('#present:') === 0) {
add(location.toString(), 'a', body).attributes.href =
location.toString();
addImage(
stage.thumbnail(stage.dimensions)
).attributes.class = 'sprite';
add(this.serializer.app, 'h4');
} else {
add(this.serializer.app, 'h4');
addImage(
stage.thumbnail(stage.dimensions)
).attributes.class = 'sprite';
}
// project notes
notes = Process.prototype.reportTextSplit(this.projectNotes, 'line');
notes.asArray().forEach(paragraph => add(paragraph));
// table of contents
add(localize('Contents'), 'h4');
toc = addNode('ul');
// sprites & stage
this.sprites.asArray().concat([stage]).forEach(sprite => {
var tocEntry = addNode('li', toc),
scripts = sprite.scripts.sortedElements(),
cl = sprite.costumes.length(),
pic,
ol;
addNode('hr');
addImage(
sprite.thumbnail(new Point(40, 40)),
tocEntry,
true
).attributes.class = 'toc';
add(sprite.name, 'a', tocEntry).attributes.href = '#' + sprite.name;
add(sprite.name, 'h2').attributes.id = sprite.name;
// if (sprite instanceof SpriteMorph || sprite.costume) {
pic = addImage(
sprite.thumbnail(sprite.extent().divideBy(stage.scale))
);
pic.attributes.class = 'sprite';
if (sprite instanceof SpriteMorph) {
if (sprite.exemplar) {
addImage(
sprite.exemplar.thumbnail(new Point(40, 40)),
add(localize('Kind of') + ' ' + sprite.exemplar.name),
true
).attributes.class = 'toc';
}
if (sprite.anchor) {
addImage(
sprite.anchor.thumbnail(new Point(40, 40)),
add(localize('Part of') + ' ' + sprite.anchor.name),
true
).attributes.class = 'toc';
}
if (sprite.parts.length) {
add(localize('Parts'), 'h3');
ol = addNode('ul');
sprite.parts.forEach(part => {
var li = addNode('li', ol, part.name);
addImage(part.thumbnail(new Point(40, 40)), li, true)
.attributes.class = 'toc';
});
}
}
// costumes
if (cl > 1 || (sprite.getCostumeIdx() !== cl)) {
add(localize('Costumes'), 'h3');
ol = addNode('ol');
sprite.costumes.asArray().forEach(costume => {
var li = addNode('li', ol, costume.name);
addImage(costume.thumbnail(new Point(40, 40)), li, true)
.attributes.class = 'toc';
});
}
// sounds
if (sprite.sounds.length()) {
add(localize('Sounds'), 'h3');
ol = addNode('ol');
sprite.sounds.asArray().forEach(sound =>
add(sound.name, 'li', ol)
);
}
// variables
addVariables(sprite.variables);
// scripts
if (scripts.length) {
add(localize('Scripts'), 'h3');
scripts.forEach(script => {
var img = addImage(script instanceof BlockMorph ?
script.scriptPic()
: script.fullImage());
img.attributes.class = 'script';
});
}
// custom blocks
addBlocks(sprite.customBlocks);
});
// globals
globalVars = stage.globalVariables();
if (Object.keys(globalVars.vars).length || stage.globalBlocks.length) {
addNode('hr');
add(
localize('For all Sprites'),
'a',
addNode('li', toc)
).attributes.href = '#global';
add(localize('For all Sprites'), 'h2').attributes.id = 'global';
// variables
addVariables(globalVars);
// custom blocks
addBlocks(stage.globalBlocks);
}
this.saveFileAs(
'<!DOCTYPE html>' + html.toString(),
'text/html;charset=utf-8',
pname
);
};
IDE_Morph.prototype.openProjectString = function (str) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening project...'),
() => {
this.rawOpenProjectString(str);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenProjectString = function (str) {
this.toggleAppMode(false);
this.spriteBar.tabBar.tabTo('scripts');
StageMorph.prototype.hiddenPrimitives = {};
StageMorph.prototype.codeMappings = {};
StageMorph.prototype.codeHeaders = {};
StageMorph.prototype.enableCodeMapping = false;
StageMorph.prototype.enableInheritance = true;
StageMorph.prototype.enableSublistIDs = false;
StageMorph.prototype.enablePenLogging = false;
Process.prototype.enableLiveCoding = false;
if (Process.prototype.isCatchingErrors) {
try {
this.serializer.openProject(
this.serializer.load(str, this),
this
);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
this.serializer.openProject(
this.serializer.load(str, this),
this
);
}
this.stopFastTracking();
};
IDE_Morph.prototype.openCloudDataString = function (str) {
var msg,
size = Math.round(str.length / 1024);
this.nextSteps([
() => msg = this.showMessage('Opening project\n' + size + ' KB...'),
() => {
this.rawOpenCloudDataString(str);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenCloudDataString = function (str) {
var model;
StageMorph.prototype.hiddenPrimitives = {};
StageMorph.prototype.codeMappings = {};
StageMorph.prototype.codeHeaders = {};
StageMorph.prototype.enableCodeMapping = false;
StageMorph.prototype.enableInheritance = true;
StageMorph.prototype.enableSublistIDs = false;
StageMorph.prototype.enablePenLogging = false;
Process.prototype.enableLiveCoding = false;
if (Process.prototype.isCatchingErrors) {
try {
model = this.serializer.parse(str);
this.serializer.loadMediaModel(model.childNamed('media'));
this.serializer.openProject(
this.serializer.loadProjectModel(
model.childNamed('project'),
this,
model.attributes.remixID
),
this
);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
model = this.serializer.parse(str);
this.serializer.loadMediaModel(model.childNamed('media'));
this.serializer.openProject(
this.serializer.loadProjectModel(
model.childNamed('project'),
this,
model.attributes.remixID
),
this
);
}
this.stopFastTracking();
};
IDE_Morph.prototype.openBlocksString = function (str, name, silently) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening blocks...'),
() => {
this.rawOpenBlocksString(str, name, silently);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenBlocksString = function (str, name, silently) {
// name is optional (string), so is silently (bool)
var blocks;
if (Process.prototype.isCatchingErrors) {
try {
blocks = this.serializer.loadBlocks(str, this.stage);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
blocks = this.serializer.loadBlocks(str, this.stage);
}
if (silently) {
blocks.forEach(def => {
def.receiver = this.stage;
this.stage.globalBlocks.push(def);
this.stage.replaceDoubleDefinitionsFor(def);
});
this.flushPaletteCache();
this.refreshPalette();
this.showMessage(
'Imported Blocks Module' + (name ? ': ' + name : '') + '.',
2
);
} else {
new BlockImportDialogMorph(blocks, this.stage, name).popUp();
}
};
IDE_Morph.prototype.openSpritesString = function (str) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening sprite...'),
() => {
this.rawOpenSpritesString(str);
msg.destroy();
},
]);
};
IDE_Morph.prototype.rawOpenSpritesString = function (str) {
if (Process.prototype.isCatchingErrors) {
try {
this.serializer.loadSprites(str, this);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
this.serializer.loadSprites(str, this);
}
};
IDE_Morph.prototype.openMediaString = function (str) {
if (Process.prototype.isCatchingErrors) {
try {
this.serializer.loadMedia(str);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
this.serializer.loadMedia(str);
}
this.showMessage('Imported Media Module.', 2);
};
IDE_Morph.prototype.openScriptString = function (str) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening script...'),
() => {
this.rawOpenScriptString(str);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenScriptString = function (str) {
var xml,
script,
scripts = this.currentSprite.scripts;
if (Process.prototype.isCatchingErrors) {
try {
xml = this.serializer.parse(str, this.currentSprite);
script = this.serializer.loadScript(xml, this.currentSprite);
} catch (err) {
this.showMessage('Load failed: ' + err);
}
} else {
xml = this.serializer.loadScript(str, this.currentSprite);
script = this.serializer.loadScript(xml, this.currentSprite);
}
script.setPosition(this.world().hand.position());
scripts.add(script);
scripts.adjustBounds();
scripts.lastDroppedBlock = script;
scripts.recordDrop(
{
origin: this.palette,
position: this.palette.center()
}
);
this.showMessage(
'Imported Script.',
2
);
};
IDE_Morph.prototype.openDataString = function (str, name, type) {
var msg;
this.nextSteps([
() => msg = this.showMessage('Opening data...'),
() => {
this.rawOpenDataString(str, name, type);
msg.destroy();
}
]);
};
IDE_Morph.prototype.rawOpenDataString = function (str, name, type) {
var data, vName, dlg,
globals = this.currentSprite.globalVariables();
function newVarName(name) {
var existing = globals.names(),
ix = name.indexOf('\('),
stem = (ix < 0) ? name : name.substring(0, ix),
count = 1,
newName = stem;
while (contains(existing, newName)) {
count += 1;
newName = stem + '(' + count + ')';
}
return newName;
}
switch (type) {
case 'csv':
data = Process.prototype.parseCSV(str);
break;
case 'json':
data = Process.prototype.parseJSON(str);
break;
default: // assume plain text
data = str;
}
vName = newVarName(name || 'data');
globals.addVar(vName);
globals.setVar(vName, data);
this.currentSprite.toggleVariableWatcher(vName, true); // global
this.flushBlocksCache('variables');
this.currentCategory = 'variables';
this.categories.children.forEach(each =>
each.refresh()
);
this.refreshPalette(true);
if (data instanceof List) {
dlg = new TableDialogMorph(data);
dlg.labelString = localize(dlg.labelString) + ': ' + vName;
dlg.createLabel();
dlg.popUp(this.world());
}
};
IDE_Morph.prototype.openProject = function (name) {
var str;
if (name) {
this.showMessage('opening project\n' + name);
this.setProjectName(name);
str = localStorage['-snap-project-' + name];
this.openProjectString(str);
this.setURL('#open:' + str);
}
};
IDE_Morph.prototype.setURL = function (str) {
// Set the URL to a project's XML contents
location.hash = this.projectsInURLs ? str : '';
};
IDE_Morph.prototype.saveFileAs = function (
contents,
fileType,
fileName
) {
/** Allow for downloading a file to a disk.
This relies the FileSaver.js library which exports saveAs()
Two utility methods saveImageAs and saveXMLAs should be used first.
*/
var blobIsSupported = false,
world = this.world(),
fileExt,
dialog;
// fileType is a <kind>/<ext>;<charset> format.
fileExt = fileType.split('/')[1].split(';')[0];
// handle text/plain as a .txt file
fileExt = '.' + (fileExt === 'plain' ? 'txt' : fileExt);
function dataURItoBlob(text, mimeType) {
var i,
data = text,
components = text.split(','),
hasTypeStr = text.indexOf('data:') === 0;
// Convert to binary data, in format Blob() can use.
if (hasTypeStr && components[0].indexOf('base64') > -1) {
text = atob(components[1]);
data = new Uint8Array(text.length);
i = text.length;
while (i--) {
data[i] = text.charCodeAt(i);
}
} else if (hasTypeStr) {
// not base64 encoded
text = text.replace(/^data:image\/.*?, */, '');
data = new Uint8Array(text.length);
i = text.length;
while (i--) {
data[i] = text.charCodeAt(i);
}
}
return new Blob([data], {type: mimeType });
}
try {
blobIsSupported = !!new Blob();
} catch (e) {}
if (blobIsSupported) {
if (!(contents instanceof Blob)) {
contents = dataURItoBlob(contents, fileType);
}
// download a file and delegate to FileSaver
// false: Do not preprend a BOM to the file.
saveAs(contents, fileName + fileExt, false);
} else {
dialog = new DialogBoxMorph();
dialog.inform(
localize('Could not export') + ' ' + fileName,
'unable to export text',
world
);
dialog.fixLayout();
}
};
IDE_Morph.prototype.saveCanvasAs = function (canvas, fileName) {
// Export a Canvas object as a PNG image
// Note: This commented out due to poor browser support.
// cavas.toBlob() is currently supported in Firefox, IE, Chrome but
// browsers prevent easily saving the generated files.
// Do not re-enable without revisiting issue #1191
// if (canvas.toBlob) {
// var myself = this;
// canvas.toBlob(function (blob) {
// myself.saveFileAs(blob, 'image/png', fileName);
// });
// return;
// }
this.saveFileAs(canvas.toDataURL(), 'image/png', fileName);
};
IDE_Morph.prototype.saveAudioAs = function (audio, fileName) {
// Export a Sound object as a WAV file
this.saveFileAs(audio.src, 'audio/wav', fileName);
};
IDE_Morph.prototype.saveXMLAs = function(xml, fileName) {
// wrapper to saving XML files with a proper type tag.
this.saveFileAs(xml, 'text/xml;chartset=utf-8', fileName);
};
IDE_Morph.prototype.switchToUserMode = function () {
var world = this.world();
world.isDevMode = false;
Process.prototype.isCatchingErrors = true;
this.controlBar.updateLabel();
this.isAutoFill = true;
this.isDraggable = false;
this.reactToWorldResize(world.bounds.copy());
this.siblings().forEach(morph => {
if (morph instanceof DialogBoxMorph) {
world.add(morph); // bring to front
} else {
morph.destroy();
}
});
this.flushBlocksCache();
this.refreshPalette();
// prevent non-DialogBoxMorphs from being dropped
// onto the World in user-mode
world.reactToDropOf = (morph) => {
if (!(morph instanceof DialogBoxMorph ||
(morph instanceof MenuMorph))) {
if (world.hand.grabOrigin) {
morph.slideBackTo(world.hand.grabOrigin);
} else {
world.hand.grab(morph);
}
}
};
this.showMessage('entering user mode', 1);
};
IDE_Morph.prototype.switchToDevMode = function () {
var world = this.world();
world.isDevMode = true;
Process.prototype.isCatchingErrors = false;
this.controlBar.updateLabel();
this.isAutoFill = false;
this.isDraggable = true;
this.setExtent(world.extent().subtract(100));
this.setPosition(world.position().add(20));
this.flushBlocksCache();
this.refreshPalette();
// enable non-DialogBoxMorphs to be dropped
// onto the World in dev-mode
delete world.reactToDropOf;
this.showMessage(
'entering development mode.\n\n'
+ 'error catching is turned off,\n'
+ 'use the browser\'s web console\n'
+ 'to see error messages.'
);
};
IDE_Morph.prototype.flushBlocksCache = function (category) {
// if no category is specified, the whole cache gets flushed
if (category) {
this.stage.blocksCache[category] = null;
this.stage.children.forEach(m => {
if (m instanceof SpriteMorph) {
m.blocksCache[category] = null;
}
});
} else {
this.stage.blocksCache = {};
this.stage.children.forEach(m => {
if (m instanceof SpriteMorph) {
m.blocksCache = {};
}
});
}
this.flushPaletteCache(category);
};
IDE_Morph.prototype.flushPaletteCache = function (category) {
// if no category is specified, the whole cache gets flushed
if (category) {
this.stage.paletteCache[category] = null;
this.stage.children.forEach(m => {
if (m instanceof SpriteMorph) {
m.paletteCache[category] = null;
}
});
} else {
this.stage.paletteCache = {};
this.stage.children.forEach(m => {
if (m instanceof SpriteMorph) {
m.paletteCache = {};
}
});
}
};
IDE_Morph.prototype.toggleZebraColoring = function () {
var scripts = [];
if (!BlockMorph.prototype.zebraContrast) {
BlockMorph.prototype.zebraContrast = 40;
} else {
BlockMorph.prototype.zebraContrast = 0;
}
// select all scripts:
this.stage.children.concat(this.stage).forEach(morph => {
if (isSnapObject(morph)) {
scripts = scripts.concat(
morph.scripts.children.filter(morph =>
morph instanceof BlockMorph
)
);
}
});
// force-update all scripts:
scripts.forEach(topBlock =>
topBlock.fixBlockColor(null, true)
);
};
IDE_Morph.prototype.toggleDynamicInputLabels = function () {
var projectData;
SyntaxElementMorph.prototype.dynamicInputLabels =
!SyntaxElementMorph.prototype.dynamicInputLabels;
if (Process.prototype.isCatchingErrors) {
try {
projectData = this.serializer.serialize(this.stage);
} catch (err) {
this.showMessage('Serialization failed: ' + err);
}
} else {
projectData = this.serializer.serialize(this.stage);
}
SpriteMorph.prototype.initBlocks();
this.spriteBar.tabBar.tabTo('scripts');
this.createCategories();
this.createCorralBar();
this.openProjectString(projectData);
};
IDE_Morph.prototype.toggleBlurredShadows = function () {
window.useBlurredShadows = !useBlurredShadows;
};
IDE_Morph.prototype.toggleLongFormInputDialog = function () {
InputSlotDialogMorph.prototype.isLaunchingExpanded =
!InputSlotDialogMorph.prototype.isLaunchingExpanded;
if (InputSlotDialogMorph.prototype.isLaunchingExpanded) {
this.saveSetting('longform', true);
} else {
this.removeSetting('longform');
}
};
IDE_Morph.prototype.togglePlainPrototypeLabels = function () {
BlockLabelPlaceHolderMorph.prototype.plainLabel =
!BlockLabelPlaceHolderMorph.prototype.plainLabel;
if (BlockLabelPlaceHolderMorph.prototype.plainLabel) {
this.saveSetting('plainprototype', true);
} else {
this.removeSetting('plainprototype');
}
};
IDE_Morph.prototype.togglePreferEmptySlotDrops = function () {
ScriptsMorph.prototype.isPreferringEmptySlots =
!ScriptsMorph.prototype.isPreferringEmptySlots;
};
IDE_Morph.prototype.toggleVirtualKeyboard = function () {
MorphicPreferences.useVirtualKeyboard =
!MorphicPreferences.useVirtualKeyboard;
};
IDE_Morph.prototype.toggleInputSliders = function () {
MorphicPreferences.useSliderForInput =
!MorphicPreferences.useSliderForInput;
};
IDE_Morph.prototype.toggleSliderExecute = function () {
ArgMorph.prototype.executeOnSliderEdit =
!ArgMorph.prototype.executeOnSliderEdit;
};
IDE_Morph.prototype.setEmbedMode = function () {
var myself = this;
this.isEmbedMode = true;
this.appModeColor = new Color(243,238,235);
this.embedOverlay = new Morph();
this.embedOverlay.color = new Color(128, 128, 128);
this.embedOverlay.alpha = 0.5;
this.embedPlayButton = new SymbolMorph('circleSolid');
this.embedPlayButton.color = new Color(64, 128, 64);
this.embedPlayButton.alpha = 0.75;
this.embedPlayButton.flag = new SymbolMorph('flag');
this.embedPlayButton.flag.color = new Color(128, 255, 128);
this.embedPlayButton.flag.alpha = 0.75;
this.embedPlayButton.add(this.embedPlayButton.flag);
this.embedPlayButton.mouseClickLeft = function () {
myself.runScripts();
myself.embedOverlay.destroy();
this.destroy();
};
this.controlBar.hide();
this.add(this.embedOverlay);
this.add(this.embedPlayButton);
this.fixLayout();
};
IDE_Morph.prototype.toggleAppMode = function (appMode) {
var world = this.world(),
elements = [
this.logo,
this.controlBar.cloudButton,
this.controlBar.projectButton,
this.controlBar.settingsButton,
this.controlBar.steppingButton,
this.controlBar.stageSizeButton,
this.paletteHandle,
this.stageHandle,
this.corral,
this.corralBar,
this.spriteEditor,
this.spriteBar,
this.palette,
this.categories
];
this.isAppMode = isNil(appMode) ? !this.isAppMode : appMode;
if (this.isAppMode) {
this.wasSingleStepping = Process.prototype.enableSingleStepping;
if (this.wasSingleStepping) {
this.toggleSingleStepping();
}
this.setColor(this.appModeColor);
this.controlBar.setColor(this.color);
this.controlBar.appModeButton.refresh();
elements.forEach(e =>
e.hide()
);
world.children.forEach(morph => {
if (morph instanceof DialogBoxMorph) {
morph.hide();
}
});
if (world.keyboardFocus instanceof ScriptFocusMorph) {
world.keyboardFocus.stopEditing();
}
} else {
if (this.wasSingleStepping && !Process.prototype.enableSingleStepping) {
this.toggleSingleStepping();
}
this.setColor(this.backgroundColor);
this.controlBar.setColor(this.frameColor);
elements.forEach(e =>
e.show()
);
this.stage.setScale(1);
// show all hidden dialogs
world.children.forEach(morph => {
if (morph instanceof DialogBoxMorph) {
morph.show();
}
});
// prevent scrollbars from showing when morph appears
world.allChildren().filter(c =>
c instanceof ScrollFrameMorph
).forEach(s =>
s.adjustScrollBars()
);
// prevent rotation and draggability controls from
// showing for the stage
if (this.currentSprite === this.stage) {
this.spriteBar.children.forEach(child => {
if (child instanceof PushButtonMorph) {
child.hide();
}
});
}
// update undrop controls
this.currentSprite.scripts.updateToolbar();
}
this.setExtent(this.world().extent());
};
IDE_Morph.prototype.toggleStageSize = function (isSmall, forcedRatio) {
var myself = this,
smallRatio = forcedRatio || 0.5,
msecs = this.isAnimating ? 100 : 0,
world = this.world(),
shiftClicked = (world.currentKey === 16),
altClicked = (world.currentKey === 18);
function toggle() {
myself.isSmallStage = isNil(isSmall) ? !myself.isSmallStage : isSmall;
}
function zoomTo(targetRatio) {
myself.isSmallStage = true;
world.animations.push(new Animation(
ratio => {
myself.stageRatio = ratio;
myself.setExtent(world.extent());
},
() => myself.stageRatio,
targetRatio - myself.stageRatio,
msecs,
null, // easing
() => {
myself.isSmallStage = (targetRatio !== 1);
myself.controlBar.stageSizeButton.refresh();
}
));
}
if (shiftClicked) {
smallRatio = SpriteIconMorph.prototype.thumbSize.x * 3 /
this.stage.dimensions.x;
if (!this.isSmallStage || (smallRatio === this.stageRatio)) {
toggle();
}
} else if (altClicked) {
smallRatio = this.width() / 2 /
this.stage.dimensions.x;
if (!this.isSmallStage || (smallRatio === this.stageRatio)) {
toggle();
}
} else {
toggle();
}
if (this.isSmallStage) {
zoomTo(smallRatio);
} else {
zoomTo(1);
}
};
IDE_Morph.prototype.setPaletteWidth = function (newWidth) {
var msecs = this.isAnimating ? 100 : 0,
world = this.world();
world.animations.push(new Animation(
newWidth => {
this.paletteWidth = newWidth;
this.setExtent(world.extent());
},
() => this.paletteWidth,
newWidth - this.paletteWidth,
msecs
));
};
IDE_Morph.prototype.createNewProject = function () {
this.confirm(
'Replace the current project with a new one?',
'New Project',
() => this.newProject()
);
};
IDE_Morph.prototype.openProjectsBrowser = function () {
if (location.protocol === 'file:') {
// bypass the project import dialog and directly pop up
// the local file picker.
// this should not be necessary, we should be able
// to access the cloud even when running Snap! locally
// to be worked on.... (jens)
this.importLocalFile();
return;
}
new ProjectDialogMorph(this, 'open').popUp();
};
IDE_Morph.prototype.saveProjectsBrowser = function () {
// temporary hack - only allow exporting projects to disk
// when running Snap! locally without a web server
if (location.protocol === 'file:') {
this.prompt(
'Export Project As...',
name => this.exportProject(name, false),
null,
'exportProject'
);
return;
}
if (this.source === 'examples') {
this.source = null; // cannot save to examples
}
new ProjectDialogMorph(this, 'save').popUp();
};
// IDE_Morph microphone settings
IDE_Morph.prototype.microphoneMenu = function () {
var menu = new MenuMorph(this),
world = this.world(),
pos = this.controlBar.settingsButton.bottomLeft(),
resolutions = ['low', 'normal', 'high', 'max'],
microphone = this.stage.microphone;
if (microphone.isReady) {
menu.addItem(
'\u2611 ' + localize('Microphone'),
() => microphone.stop()
);
menu.addLine();
}
resolutions.forEach((res, i) => {
menu.addItem(
(microphone.resolution === i + 1 ? '\u2713 ' : ' ') +
localize(res),
() => microphone.setResolution(i + 1)
);
});
menu.popup(world, pos);
};
// IDE_Morph localization
IDE_Morph.prototype.languageMenu = function () {
var menu = new MenuMorph(this),
world = this.world(),
pos = this.controlBar.settingsButton.bottomLeft();
SnapTranslator.languages().forEach(lang =>
menu.addItem(
(SnapTranslator.language === lang ? '\u2713 ' : ' ') +
SnapTranslator.languageName(lang),
() => {
this.loadNewProject = false;
this.setLanguage(lang);
}
)
);
menu.popup(world, pos);
};
IDE_Morph.prototype.setLanguage = function (lang, callback, noSave) {
var translation = document.getElementById('language'),
src = this.resourceURL('locale', 'lang-' + lang + '.js');
SnapTranslator.unload();
if (translation) {
document.head.removeChild(translation);
}
if (lang === 'en') {
return this.reflectLanguage('en', callback, noSave);
}
translation = document.createElement('script');
translation.id = 'language';
translation.onload = () => this.reflectLanguage(lang, callback, noSave);
document.head.appendChild(translation);
translation.src = src;
};
IDE_Morph.prototype.reflectLanguage = function (lang, callback, noSave) {
var projectData,
urlBar = location.hash;
SnapTranslator.language = lang;
if (!this.loadNewProject) {
if (Process.prototype.isCatchingErrors) {
try {
projectData = this.serializer.serialize(this.stage);
} catch (err) {
this.showMessage('Serialization failed: ' + err);
}
} else {
projectData = this.serializer.serialize(this.stage);
}
}
SpriteMorph.prototype.initBlocks();
this.spriteBar.tabBar.tabTo('scripts');
this.createCategories();
this.createCorralBar();
this.fixLayout();
if (this.loadNewProject) {
this.newProject();
location.hash = urlBar;
} else {
this.openProjectString(projectData);
}
if (!noSave) {
this.saveSetting('language', lang);
}
if (callback) {callback.call(this); }
};
// IDE_Morph blocks scaling
IDE_Morph.prototype.userSetBlocksScale = function () {
var scrpt,
blck,
shield,
sample,
action;
scrpt = new CommandBlockMorph();
scrpt.color = SpriteMorph.prototype.blockColor.motion;
scrpt.setSpec(localize('build'));
blck = new CommandBlockMorph();
blck.color = SpriteMorph.prototype.blockColor.sound;
blck.setSpec(localize('your own'));
scrpt.nextBlock(blck);
blck = new CommandBlockMorph();
blck.color = SpriteMorph.prototype.blockColor.operators;
blck.setSpec(localize('blocks'));
scrpt.bottomBlock().nextBlock(blck);
/*
blck = SpriteMorph.prototype.blockForSelector('doForever');
blck.inputs()[0].nestedBlock(scrpt);
*/
sample = new FrameMorph();
sample.acceptsDrops = false;
sample.color = IDE_Morph.prototype.groupColor;
sample.cachedTexture = this.scriptsPaneTexture;
sample.setExtent(new Point(250, 180));
scrpt.setPosition(sample.position().add(10));
sample.add(scrpt);
shield = new Morph();
shield.alpha = 0;
shield.setExtent(sample.extent());
shield.setPosition(sample.position());
sample.add(shield);
action = (num) => {
scrpt.blockSequence().forEach(block => {
block.setScale(num);
block.setSpec(block.blockSpec);
});
scrpt.fullChanged();
};
new DialogBoxMorph(
null,
num => this.setBlocksScale(Math.min(num, 12))
).withKey('zoomBlocks').prompt(
'Zoom blocks',
SyntaxElementMorph.prototype.scale.toString(),
this.world(),
sample, // pic
{
'normal (1x)' : 1,
'demo (1.2x)' : 1.2,
'presentation (1.4x)' : 1.4,
'big (2x)' : 2,
'huge (4x)' : 4,
'giant (8x)' : 8,
'monstrous (10x)' : 10
},
false, // read only?
true, // numeric
1, // slider min
5, // slider max
action // slider action
);
};
IDE_Morph.prototype.setBlocksScale = function (num) {
var projectData;
if (Process.prototype.isCatchingErrors) {
try {
projectData = this.serializer.serialize(this.stage);
} catch (err) {
this.showMessage('Serialization failed: ' + err);
}
} else {
projectData = this.serializer.serialize(this.stage);
}
SyntaxElementMorph.prototype.setScale(num);
CommentMorph.prototype.refreshScale();
SpriteMorph.prototype.initBlocks();
this.spriteBar.tabBar.tabTo('scripts');
this.createCategories();
this.createCorralBar();
this.fixLayout();
this.openProjectString(projectData);
this.saveSetting('zoom', num);
};
// IDE_Morph stage size manipulation
IDE_Morph.prototype.userSetStageSize = function () {
new DialogBoxMorph(
this,
this.setStageExtent,
this
).promptVector(
"Stage size",
StageMorph.prototype.dimensions,
new Point(480, 360),
'Stage width',
'Stage height',
this.world(),
null, // pic
null // msg
);
};
IDE_Morph.prototype.setStageExtent = function (aPoint) {
var myself = this,
world = this.world(),
ext = aPoint.max(new Point(240, 180));
function zoom() {
myself.step = function () {
var delta = ext.subtract(
StageMorph.prototype.dimensions
).divideBy(2);
if (delta.abs().lt(new Point(5, 5))) {
StageMorph.prototype.dimensions = ext;
delete myself.step;
} else {
StageMorph.prototype.dimensions =
StageMorph.prototype.dimensions.add(delta);
}
myself.stage.setExtent(StageMorph.prototype.dimensions);
myself.stage.clearPenTrails();
myself.fixLayout();
this.setExtent(world.extent());
};
}
this.stageRatio = 1;
this.isSmallStage = false;
this.controlBar.stageSizeButton.refresh();
this.stage.stopVideo();
this.setExtent(world.extent());
if (this.isAnimating) {
zoom();
} else {
StageMorph.prototype.dimensions = ext;
this.stage.setExtent(StageMorph.prototype.dimensions);
this.stage.clearPenTrails();
this.fixLayout();
this.setExtent(world.extent());
}
};
// IDE_Morph dragging threshold (internal feature)
IDE_Morph.prototype.userSetDragThreshold = function () {
new DialogBoxMorph(
this,
num => MorphicPreferences.grabThreshold = Math.min(
Math.max(+num, 0),
200
),
this
).prompt(
"Dragging threshold",
MorphicPreferences.grabThreshold.toString(),
this.world(),
null, // pic
null, // choices
null, // read only
true // numeric
);
};
// IDE_Morph cloud interface
IDE_Morph.prototype.initializeCloud = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.login(
user.username.toLowerCase(),
user.password,
user.choice,
(username, role, response) => {
sessionStorage.username = username;
this.source = 'cloud';
if (!isNil(response.days_left)) {
new DialogBoxMorph().inform(
'Unverified account: ' +
response.days_left +
' days left',
'You are now logged in, and your account\n' +
'is enabled for three days.\n' +
'Please use the verification link that\n' +
'was sent to your email address when you\n' +
'signed up.\n\n' +
'If you cannot find that email, please\n' +
'check your spam folder. If you still\n' +
'cannot find it, please use the "Resend\n' +
'Verification Email..." option in the cloud\n' +
'menu.\n\n' +
'You have ' + response.days_left + ' days left.',
world,
this.cloudIcon(null, new Color(0, 180, 0))
);
} else {
this.showMessage(response.message, 2);
}
},
this.cloudError()
)
).withKey('cloudlogin').promptCredentials(
'Sign in',
'login',
null,
null,
null,
null,
'stay signed in on this computer\nuntil logging out',
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.createCloudAccount = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.signup(
user.username,
user.password,
user.passwordRepeat,
user.email,
(txt, title) => new DialogBoxMorph().inform(
title,
txt + '.\n\nYou can now log in.',
world,
this.cloudIcon(null, new Color(0, 180, 0))
),
this.cloudError()
)
).withKey('cloudsignup').promptCredentials(
'Sign up',
'signup',
'https://snap.berkeley.edu/tos.html',
'Terms of Service...',
'https://snap.berkeley.edu/privacy.html',
'Privacy...',
'I have read and agree\nto the Terms of Service',
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.resetCloudPassword = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.resetPassword(
user.username,
(txt, title) => new DialogBoxMorph().inform(
title,
txt +
'\n\nAn e-mail with a link to\n' +
'reset your password\n' +
'has been sent to the address provided',
world,
this.cloudIcon(null, new Color(0, 180, 0))
),
this.cloudError()
)
).withKey('cloudresetpassword').promptCredentials(
'Reset password',
'resetPassword',
null,
null,
null,
null,
null,
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.resendVerification = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.resendVerification(
user.username,
(txt, title) => new DialogBoxMorph().inform(
title,
txt,
world,
this.cloudIcon(null, new Color(0, 180, 0))
),
this.cloudError()
)
).withKey('cloudresendverification').promptCredentials(
'Resend verification email',
'resendVerification',
null,
null,
null,
null,
null,
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.changeCloudPassword = function () {
var world = this.world();
new DialogBoxMorph(
null,
user => this.cloud.changePassword(
user.oldpassword,
user.password,
user.passwordRepeat,
() => this.showMessage('password has been changed.', 2),
this.cloudError()
)
).withKey('cloudpassword').promptCredentials(
'Change Password',
'changePassword',
null,
null,
null,
null,
null,
world,
this.cloudIcon(),
this.cloudMsg
);
};
IDE_Morph.prototype.logout = function () {
this.cloud.logout(
() => {
delete(sessionStorage.username);
this.showMessage('disconnected.', 2);
},
() => {
delete(sessionStorage.username);
this.showMessage('disconnected.', 2);
}
);
};
IDE_Morph.prototype.buildProjectRequest = function () {
var xml = this.serializer.serialize(this.stage),
thumbnail = normalizeCanvas(
this.stage.thumbnail(
SnapSerializer.prototype.thumbnailSize
)).toDataURL(),
body;
this.serializer.isCollectingMedia = true;
body = {
notes: this.projectNotes,
xml: xml,
media: this.hasChangedMedia ?
this.serializer.mediaXML(this.projectName) : null,
thumbnail: thumbnail,
remixID: this.stage.remixID
};
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
return body;
};
IDE_Morph.prototype.verifyProject = function (body) {
// Ensure the project is less than 10MB and serializes correctly.
var encodedBody = JSON.stringify(body);
if (encodedBody.length > Cloud.MAX_FILE_SIZE) {
new DialogBoxMorph().inform(
'Snap!Cloud - Cannot Save Project',
'The media inside this project exceeds 10 MB.\n' +
'Please reduce the size of costumes or sounds.\n',
this.world(),
this.cloudIcon(null, new Color(180, 0, 0))
);
return false;
}
// console.log(encodedBody.length);
// check if serialized data can be parsed back again
try {
this.serializer.parse(body.xml);
} catch (err) {
this.showMessage('Serialization of program data failed:\n' + err);
return false;
}
if (body.media !== null) {
try {
this.serializer.parse(body.media);
} catch (err) {
this.showMessage('Serialization of media failed:\n' + err);
return false;
}
}
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
return encodedBody.length;
};
IDE_Morph.prototype.saveProjectToCloud = function (name) {
var projectBody, projectSize;
if (name) {
this.setProjectName(name);
}
this.showMessage('Saving project\nto the cloud...');
projectBody = this.buildProjectRequest();
projectSize = this.verifyProject(projectBody);
if (!projectSize) {return; } // Invalid Projects don't return anything.
this.showMessage(
'Uploading ' + Math.round(projectSize / 1024) + ' KB...'
);
this.cloud.saveProject(
this.projectName,
projectBody,
() => this.showMessage('saved.', 2),
this.cloudError()
);
};
IDE_Morph.prototype.exportProjectMedia = function (name) {
var menu, media;
this.serializer.isCollectingMedia = true;
if (name) {
this.setProjectName(name);
try {
menu = this.showMessage('Exporting');
media = this.serializer.mediaXML(name);
this.saveXMLAs(media, this.projectName + ' media');
menu.destroy();
this.showMessage('Exported!', 1);
} catch (err) {
if (Process.prototype.isCatchingErrors) {
this.serializer.isCollectingMedia = false;
this.showMessage('Export failed: ' + err);
} else {
throw err;
}
}
}
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
// this.hasChangedMedia = false;
};
IDE_Morph.prototype.exportProjectNoMedia = function (name) {
var menu, str;
this.serializer.isCollectingMedia = true;
if (name) {
this.setProjectName(name);
if (Process.prototype.isCatchingErrors) {
try {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
this.saveXMLAs(str, this.projectName);
menu.destroy();
this.showMessage('Exported!', 1);
} catch (err) {
this.serializer.isCollectingMedia = false;
this.showMessage('Export failed: ' + err);
}
} else {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
this.saveXMLAs(str, this.projectName);
menu.destroy();
this.showMessage('Exported!', 1);
}
}
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
};
IDE_Morph.prototype.exportProjectAsCloudData = function (name) {
var menu, str, media, dta;
this.serializer.isCollectingMedia = true;
if (name) {
this.setProjectName(name);
if (Process.prototype.isCatchingErrors) {
try {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
media = this.serializer.mediaXML(name);
dta = '<snapdata>' + str + media + '</snapdata>';
this.saveXMLAs(str, this.projectName);
menu.destroy();
this.showMessage('Exported!', 1);
} catch (err) {
this.serializer.isCollectingMedia = false;
this.showMessage('Export failed: ' + err);
}
} else {
menu = this.showMessage('Exporting');
str = this.serializer.serialize(this.stage);
media = this.serializer.mediaXML(name);
dta = '<snapdata>' + str + media + '</snapdata>';
this.saveXMLAs(str, this.projectName);
menu.destroy();
this.showMessage('Exported!', 1);
}
}
this.serializer.isCollectingMedia = false;
this.serializer.flushMedia();
// this.hasChangedMedia = false;
};
IDE_Morph.prototype.cloudAcknowledge = function () {
var myself = this;
return function (responseText, url) {
nop(responseText);
new DialogBoxMorph().inform(
'Cloud Connection',
'Successfully connected to:\n'
+ 'http://'
+ url,
myself.world(),
myself.cloudIcon(null, new Color(0, 180, 0))
);
};
};
IDE_Morph.prototype.cloudResponse = function () {
var myself = this;
return function (responseText, url) {
var response = responseText;
if (response.length > 50) {
response = response.substring(0, 50) + '...';
}
new DialogBoxMorph().inform(
'Snap!Cloud',
'http://'
+ url + ':\n\n'
+ 'responds:\n'
+ response,
myself.world(),
myself.cloudIcon(null, new Color(0, 180, 0))
);
};
};
IDE_Morph.prototype.cloudError = function () {
var myself = this;
// try finding an eplanation what's going on
// has some issues, commented out for now
/*
function getURL(url) {
try {
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send();
if (request.status === 200) {
return request.responseText;
}
return null;
} catch (err) {
return null;
}
}
*/
return function (responseText, url) {
// first, try to find out an explanation for the error
// and notify the user about it,
// if none is found, show an error dialog box
var response = responseText,
// explanation = getURL('https://snap.berkeley.edu/cloudmsg.txt'),
explanation = null;
if (myself.shield) {
myself.shield.destroy();
myself.shield = null;
}
if (explanation) {
myself.showMessage(explanation);
return;
}
new DialogBoxMorph().inform(
'Snap!Cloud',
(url ? url + '\n' : '')
+ response,
myself.world(),
myself.cloudIcon(null, new Color(180, 0, 0))
);
};
};
IDE_Morph.prototype.cloudIcon = function (height, color) {
var clr = color || DialogBoxMorph.prototype.titleBarColor,
isFlat = MorphicPreferences.isFlat,
icon = new SymbolMorph(
isFlat ? 'cloud' : 'cloudGradient',
height || 50,
clr,
isFlat ? null : new Point(-1, -1),
clr.darker(50)
);
if (!isFlat) {
icon.addShadow(new Point(1, 1), 1, clr.lighter(95));
}
return icon;
};
IDE_Morph.prototype.setCloudURL = function () {
var myself = this;
new DialogBoxMorph(
null,
function (url) {
myself.cloud.url = url;
}
).withKey('cloudURL').prompt(
'Cloud URL',
this.cloud.url,
this.world(),
null,
this.cloud.knownDomains
);
};
IDE_Morph.prototype.urlParameters = function () {
var parameters = location.hash.slice(location.hash.indexOf(':') + 1);
return this.cloud.parseDict(parameters);
};
IDE_Morph.prototype.hasCloudProject = function () {
var params = this.urlParameters();
return params.hasOwnProperty('Username') &&
params.hasOwnProperty('ProjectName');
};
// IDE_Morph HTTP data fetching
IDE_Morph.prototype.getURL = function (url, callback, responseType) {
// fetch the contents of a url and pass it into the specified callback.
// If no callback is specified synchronously fetch and return it
// Note: Synchronous fetching has been deprecated and should be switched
var request = new XMLHttpRequest(),
async = callback instanceof Function,
myself = this,
rsp;
if (async) {
request.responseType = responseType || 'text';
}
rsp = (!async || request.responseType === 'text') ? 'responseText'
: 'response';
try {
request.open('GET', url, async);
if (async) {
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request[rsp]) {
callback.call(
myself,
request[rsp]
);
} else {
throw new Error('unable to retrieve ' + url);
}
}
};
}
// cache-control, commented out for now
// added for Snap4Arduino but has issues with local robot servers
// request.setRequestHeader('Cache-Control', 'max-age=0');
request.send();
if (!async) {
if (request.status === 200) {
return request[rsp];
}
throw new Error('unable to retrieve ' + url);
}
} catch (err) {
myself.showMessage(err.toString());
if (async) {
callback.call(this);
} else {
return request[rsp];
}
}
};
// IDE_Morph user dialog shortcuts
IDE_Morph.prototype.showMessage = function (message, secs) {
var m = new MenuMorph(null, message),
intervalHandle;
m.popUpCenteredInWorld(this.world());
if (secs) {
intervalHandle = setInterval(function () {
m.destroy();
clearInterval(intervalHandle);
}, secs * 1000);
}
return m;
};
IDE_Morph.prototype.inform = function (title, message) {
new DialogBoxMorph().inform(
title,
localize(message),
this.world()
);
};
IDE_Morph.prototype.confirm = function (message, title, action) {
new DialogBoxMorph(null, action).askYesNo(
title,
localize(message),
this.world()
);
};
IDE_Morph.prototype.prompt = function (message, callback, choices, key) {
(new DialogBoxMorph(null, callback)).withKey(key).prompt(
message,
'',
this.world(),
null,
choices
);
};
// IDE_Morph bracing against IE
IDE_Morph.prototype.warnAboutIE = function () {
var dlg, txt;
if (this.isIE()) {
dlg = new DialogBoxMorph();
txt = new TextMorph(
'Please do not use Internet Explorer.\n' +
'Snap! runs best in a web-standards\n' +
'compliant browser',
dlg.fontSize,
dlg.fontStyle,
true,
false,
'center',
null,
null,
MorphicPreferences.isFlat ? null : new Point(1, 1),
new Color(255, 255, 255)
);
dlg.key = 'IE-Warning';
dlg.labelString = "Internet Explorer";
dlg.createLabel();
dlg.addBody(txt);
dlg.fixLayout();
dlg.popUp(this.world());
}
};
IDE_Morph.prototype.isIE = function () {
var ua = navigator.userAgent;
return ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
};
// ProjectDialogMorph ////////////////////////////////////////////////////
// ProjectDialogMorph inherits from DialogBoxMorph:
ProjectDialogMorph.prototype = new DialogBoxMorph();
ProjectDialogMorph.prototype.constructor = ProjectDialogMorph;
ProjectDialogMorph.uber = DialogBoxMorph.prototype;
// ProjectDialogMorph instance creation:
function ProjectDialogMorph(ide, label) {
this.init(ide, label);
}
ProjectDialogMorph.prototype.init = function (ide, task) {
var myself = this;
// additional properties:
this.ide = ide;
this.task = task || 'open'; // String describing what do do (open, save)
this.source = ide.source;
this.projectList = []; // [{name: , thumb: , notes:}]
this.handle = null;
this.srcBar = null;
this.nameField = null;
this.filterField = null;
this.magnifyingGlass = null;
this.listField = null;
this.preview = null;
this.notesText = null;
this.notesField = null;
this.deleteButton = null;
this.shareButton = null;
this.unshareButton = null;
this.publishButton = null;
this.unpublishButton = null;
this.recoverButton = null;
// initialize inherited properties:
ProjectDialogMorph.uber.init.call(
this,
this, // target
null, // function
null // environment
);
// override inherited properites:
this.labelString = this.task === 'save' ? 'Save Project' : 'Open Project';
this.createLabel();
this.key = 'project' + task;
// build contents
if (task === 'open' && this.source === 'disk') {
// give the user a chance to switch to another source
this.source = null;
this.buildContents();
this.projectList = [];
this.listField.hide();
this.source = 'disk';
} else {
this.buildContents();
this.onNextStep = function () { // yield to show "updating" message
myself.setSource(myself.source);
};
}
};
ProjectDialogMorph.prototype.buildContents = function () {
var thumbnail, notification;
this.addBody(new Morph());
this.body.color = this.color;
this.srcBar = new AlignmentMorph('column', this.padding / 2);
if (this.ide.cloudMsg) {
notification = new TextMorph(
this.ide.cloudMsg,
10,
null, // style
false, // bold
null, // italic
null, // alignment
null, // width
null, // font name
new Point(1, 1), // shadow offset
new Color(255, 255, 255) // shadowColor
);
notification.refresh = nop;
this.srcBar.add(notification);
}
this.addSourceButton('cloud', localize('Cloud'), 'cloud');
if (this.task === 'open') {
this.buildFilterField();
this.addSourceButton('examples', localize('Examples'), 'poster');
if (this.hasLocalProjects() || this.ide.world().currentKey === 16) {
// shift- clicked
this.addSourceButton('local', localize('Browser'), 'globe');
}
}
this.addSourceButton('disk', localize('Computer'), 'storage');
this.srcBar.fixLayout();
this.body.add(this.srcBar);
if (this.task === 'save') {
this.nameField = new InputFieldMorph(this.ide.projectName);
this.body.add(this.nameField);
}
this.listField = new ListMorph([]);
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.body.add(this.listField);
this.preview = new Morph();
this.preview.fixLayout = nop;
this.preview.edge = InputFieldMorph.prototype.edge;
this.preview.fontSize = InputFieldMorph.prototype.fontSize;
this.preview.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.preview.contrast = InputFieldMorph.prototype.contrast;
this.preview.render = function (ctx) {
InputFieldMorph.prototype.render.call(this, ctx);
if (this.texture) {
this.renderTexture(this.texture, ctx);
}
};
this.preview.renderCachedTexture = function (ctx) {
ctx.drawImage(this.cachedTexture, this.edge, this.edge);
};
this.preview.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.preview.setExtent(
this.ide.serializer.thumbnailSize.add(this.preview.edge * 2)
);
this.body.add(this.preview);
if (this.task === 'save') {
thumbnail = this.ide.stage.thumbnail(
SnapSerializer.prototype.thumbnailSize
);
this.preview.texture = null;
this.preview.cachedTexture = thumbnail;
this.preview.rerender();
}
this.notesField = new ScrollFrameMorph();
this.notesField.fixLayout = nop;
this.notesField.edge = InputFieldMorph.prototype.edge;
this.notesField.fontSize = InputFieldMorph.prototype.fontSize;
this.notesField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.notesField.contrast = InputFieldMorph.prototype.contrast;
this.notesField.render = InputFieldMorph.prototype.render;
this.notesField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.notesField.acceptsDrops = false;
this.notesField.contents.acceptsDrops = false;
if (this.task === 'open') {
this.notesText = new TextMorph('');
} else { // 'save'
this.notesText = new TextMorph(this.ide.projectNotes);
this.notesText.isEditable = true;
this.notesText.enableSelecting();
}
this.notesField.isTextLineWrapping = true;
this.notesField.padding = 3;
this.notesField.setContents(this.notesText);
this.notesField.setWidth(this.preview.width());
this.body.add(this.notesField);
if (this.task === 'open') {
this.addButton('openProject', 'Open');
this.action = 'openProject';
this.recoverButton = this.addButton('recoveryDialog', 'Recover', true);
this.recoverButton.hide();
} else { // 'save'
this.addButton('saveProject', 'Save');
this.action = 'saveProject';
}
this.shareButton = this.addButton('shareProject', 'Share', true);
this.unshareButton = this.addButton('unshareProject', 'Unshare', true);
this.shareButton.hide();
this.unshareButton.hide();
this.publishButton = this.addButton('publishProject', 'Publish', true);
this.unpublishButton = this.addButton(
'unpublishProject',
'Unpublish',
true
);
this.publishButton.hide();
this.unpublishButton.hide();
this.deleteButton = this.addButton('deleteProject', 'Delete');
this.addButton('cancel', 'Cancel');
if (notification) {
this.setExtent(new Point(500, 360).add(notification.extent()));
} else {
this.setExtent(new Point(500, 360));
}
this.fixLayout();
};
ProjectDialogMorph.prototype.popUp = function (wrrld) {
var world = wrrld || this.ide.world();
if (world) {
ProjectDialogMorph.uber.popUp.call(this, world);
this.handle = new HandleMorph(
this,
350,
330,
this.corner,
this.corner
);
}
};
// ProjectDialogMorph action buttons
ProjectDialogMorph.prototype.createButtons = function () {
if (this.buttons) {
this.buttons.destroy();
}
this.buttons = new AlignmentMorph('column', this.padding / 3);
this.buttons.bottomRow = new AlignmentMorph('row', this.padding);
this.buttons.topRow = new AlignmentMorph('row', this.padding);
this.buttons.add(this.buttons.topRow);
this.buttons.add(this.buttons.bottomRow);
this.add(this.buttons);
this.buttons.fixLayout = function () {
if (this.topRow.children.some(function (any) {
return any.isVisible;
})) {
this.topRow.show();
this.topRow.fixLayout();
} else {
this.topRow.hide();
}
this.bottomRow.fixLayout();
AlignmentMorph.prototype.fixLayout.call(this);
};
};
ProjectDialogMorph.prototype.addButton = function (action, label, topRow) {
var button = new PushButtonMorph(
this,
action || 'ok',
' ' + localize((label || 'OK')) + ' '
);
button.fontSize = this.buttonFontSize;
button.corner = this.buttonCorner;
button.edge = this.buttonEdge;
button.outline = this.buttonOutline;
button.outlineColor = this.buttonOutlineColor;
button.outlineGradient = this.buttonOutlineGradient;
button.padding = this.buttonPadding;
button.contrast = this.buttonContrast;
button.fixLayout();
if (topRow) {
this.buttons.topRow.add(button);
} else {
this.buttons.bottomRow.add(button);
}
return button;
};
// ProjectDialogMorph source buttons
ProjectDialogMorph.prototype.addSourceButton = function (
source,
label,
symbol
) {
var myself = this,
lbl1 = new StringMorph(
label,
10,
null,
true,
null,
null,
new Point(1, 1),
new Color(255, 255, 255)
),
lbl2 = new StringMorph(
label,
10,
null,
true,
null,
null,
new Point(-1, -1),
this.titleBarColor.darker(50),
new Color(255, 255, 255)
),
l1 = new Morph(),
l2 = new Morph(),
button;
lbl1.add(new SymbolMorph(
symbol,
24,
this.titleBarColor.darker(20),
new Point(1, 1),
this.titleBarColor.darker(50)
));
lbl1.children[0].setCenter(lbl1.center());
lbl1.children[0].setBottom(lbl1.top() - this.padding / 2);
l1.isCachingImage = true;
l1.cachedImage = lbl1.fullImage();
l1.bounds = lbl1.fullBounds();
lbl2.add(new SymbolMorph(
symbol,
24,
new Color(255, 255, 255),
new Point(-1, -1),
this.titleBarColor.darker(50)
));
lbl2.children[0].setCenter(lbl2.center());
lbl2.children[0].setBottom(lbl2.top() - this.padding / 2);
l2.isCachingImage = true;
l2.cachedImage = lbl2.fullImage();
l2.bounds = lbl2.fullBounds();
button = new ToggleButtonMorph(
null, //colors,
myself, // the ProjectDialog is the target
function () { // action
myself.setSource(source);
},
[l1, l2],
function () { // query
return myself.source === source;
}
);
button.corner = this.buttonCorner;
button.edge = this.buttonEdge;
button.outline = this.buttonOutline;
button.outlineColor = this.buttonOutlineColor;
button.outlineGradient = this.buttonOutlineGradient;
button.labelMinExtent = new Point(60, 0);
button.padding = this.buttonPadding;
button.contrast = this.buttonContrast;
button.pressColor = this.titleBarColor.darker(20);
button.fixLayout();
button.refresh();
this.srcBar.add(button);
};
// ProjectDialogMorph list field control
ProjectDialogMorph.prototype.fixListFieldItemColors = function () {
// remember to always fixLayout() afterwards for the changes
// to take effect
var myself = this;
this.listField.contents.children[0].alpha = 0;
this.listField.contents.children[0].children.forEach(function (item) {
item.pressColor = myself.titleBarColor.darker(20);
item.color = new Color(0, 0, 0, 0);
});
};
// ProjectDialogMorph filter field
ProjectDialogMorph.prototype.buildFilterField = function () {
var myself = this;
this.filterField = new InputFieldMorph('');
this.magnifyingGlass =
new SymbolMorph(
'magnifyingGlass',
this.filterField.height(),
this.titleBarColor.darker(50));
this.body.add(this.magnifyingGlass);
this.body.add(this.filterField);
this.filterField.reactToInput = function (evt) {
var text = this.getValue();
myself.listField.elements =
myself.projectList.filter(function (aProject) {
var name = aProject.projectname || aProject.name,
notes = aProject.notes || '';
return name.toLowerCase().indexOf(text.toLowerCase()) > -1 ||
notes.toLowerCase().indexOf(text.toLowerCase()) > -1;
});
if (myself.listField.elements.length === 0) {
myself.listField.elements.push('(no matches)');
}
myself.clearDetails();
myself.listField.buildListContents();
myself.fixListFieldItemColors();
myself.listField.adjustScrollBars();
myself.listField.scrollY(myself.listField.top());
myself.fixLayout();
};
};
// ProjectDialogMorph ops
ProjectDialogMorph.prototype.setSource = function (source) {
var myself = this,
msg;
this.source = source;
this.srcBar.children.forEach(function (button) {
button.refresh();
});
switch (this.source) {
case 'cloud':
msg = myself.ide.showMessage('Updating\nproject list...');
this.projectList = [];
myself.ide.cloud.getProjectList(
function (response) {
// Don't show cloud projects if user has since switched panes.
if (myself.source === 'cloud') {
myself.installCloudProjectList(response.projects);
}
msg.destroy();
},
function (err, lbl) {
msg.destroy();
myself.ide.cloudError().call(null, err, lbl);
}
);
return;
case 'examples':
this.projectList = this.getExamplesProjectList();
break;
case 'local':
// deprecated, only for reading
this.projectList = this.getLocalProjectList();
break;
case 'disk':
if (this.task === 'save') {
this.projectList = [];
} else {
this.destroy();
this.ide.importLocalFile();
return;
}
break;
}
this.listField.destroy();
this.listField = new ListMorph(
this.projectList,
this.projectList.length > 0 ?
function (element) {
return element.name || element;
} : null,
null,
function () {myself.ok(); }
);
if (this.source === 'disk') {
this.listField.hide();
}
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
if (this.source === 'local') {
this.listField.action = function (item) {
var src, xml;
if (item === undefined) {return; }
if (myself.nameField) {
myself.nameField.setContents(item.name || '');
}
if (myself.task === 'open') {
src = localStorage['-snap-project-' + item.name];
if (src) {
xml = myself.ide.serializer.parse(src);
myself.notesText.text = xml.childNamed('notes').contents
|| '';
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
myself.preview.texture =
xml.childNamed('thumbnail').contents || null;
myself.preview.cachedTexture = null;
myself.preview.rerender();
}
}
myself.edit();
};
} else { // 'examples'; 'cloud' is initialized elsewhere
this.listField.action = function (item) {
var src, xml;
if (item === undefined) {return; }
if (myself.nameField) {
myself.nameField.setContents(item.name || '');
}
src = myself.ide.getURL(
myself.ide.resourceURL('Examples', item.fileName)
);
xml = myself.ide.serializer.parse(src);
myself.notesText.text = xml.childNamed('notes').contents
|| '';
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
myself.preview.texture = xml.childNamed('thumbnail').contents
|| null;
myself.preview.cachedTexture = null;
myself.preview.rerender();
myself.edit();
};
}
this.body.add(this.listField);
this.shareButton.hide();
this.unshareButton.hide();
if (this.task === 'open') {
this.recoverButton.hide();
}
this.publishButton.hide();
this.unpublishButton.hide();
if (this.source === 'local') {
this.deleteButton.show();
} else { // examples
this.deleteButton.hide();
}
this.buttons.fixLayout();
this.fixLayout();
if (this.task === 'open') {
this.clearDetails();
}
};
ProjectDialogMorph.prototype.hasLocalProjects = function () {
// check and report whether old projects still exist in the
// browser's local storage, which as of v5 has been deprecated,
// so the user can recover and move them elsewhere
return Object.keys(localStorage).some(function (any) {
return any.indexOf('-snap-project-') === 0;
});
};
ProjectDialogMorph.prototype.getLocalProjectList = function () {
var stored, name, dta,
projects = [];
for (stored in localStorage) {
if (Object.prototype.hasOwnProperty.call(localStorage, stored)
&& stored.substr(0, 14) === '-snap-project-') {
name = stored.substr(14);
dta = {
name: name,
thumb: null,
notes: null
};
projects.push(dta);
}
}
projects.sort(function (x, y) {
return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1;
});
return projects;
};
ProjectDialogMorph.prototype.getExamplesProjectList = function () {
return this.ide.getMediaList('Examples');
};
ProjectDialogMorph.prototype.installCloudProjectList = function (pl) {
var myself = this;
this.projectList = pl[0] ? pl : [];
this.projectList.sort(function (x, y) {
return x.projectname.toLowerCase() < y.projectname.toLowerCase() ?
-1 : 1;
});
this.listField.destroy();
this.listField = new ListMorph(
this.projectList,
this.projectList.length > 0 ?
function (element) {
return element.projectname || element;
} : null,
[ // format: display shared project names bold
[
'bold',
function (proj) { return proj.ispublic; }
],
[
'italic',
function (proj) { return proj.ispublished; }
]
],
function () { myself.ok(); }
);
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.listField.action = function (item) {
if (item === undefined) {return; }
if (myself.nameField) {
myself.nameField.setContents(item.projectname || '');
}
if (myself.task === 'open') {
myself.notesText.text = item.notes || '';
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
myself.preview.texture = '';
myself.preview.rerender();
// we ask for the thumbnail when selecting a project
myself.ide.cloud.getThumbnail(
null, // username is implicit
item.projectname,
function (thumbnail) {
myself.preview.texture = thumbnail;
myself.preview.cachedTexture = null;
myself.preview.rerender();
});
(new SpeechBubbleMorph(new TextMorph(
localize('last changed') + '\n' + item.lastupdated,
null,
null,
null,
null,
'center'
))).popUp(
myself.world(),
myself.preview.rightCenter().add(new Point(2, 0))
);
}
if (item.ispublic) {
myself.shareButton.hide();
myself.unshareButton.show();
if (item.ispublished) {
myself.publishButton.hide();
myself.unpublishButton.show();
} else {
myself.publishButton.show();
myself.unpublishButton.hide();
}
} else {
myself.unshareButton.hide();
myself.shareButton.show();
myself.publishButton.hide();
myself.unpublishButton.hide();
}
myself.buttons.fixLayout();
myself.fixLayout();
myself.edit();
};
this.body.add(this.listField);
if (this.task === 'open') {
this.recoverButton.show();
}
this.shareButton.show();
this.unshareButton.hide();
this.deleteButton.show();
this.buttons.fixLayout();
this.fixLayout();
if (this.task === 'open') {
this.clearDetails();
}
};
ProjectDialogMorph.prototype.clearDetails = function () {
this.notesText.text = '';
this.notesText.rerender();
this.notesField.contents.adjustBounds();
this.preview.texture = null;
this.preview.cachedTexture = null;
this.preview.rerender();
};
ProjectDialogMorph.prototype.recoveryDialog = function () {
var proj = this.listField.selected;
if (!proj) {return; }
new ProjectRecoveryDialogMorph(this.ide, proj.projectname, this).popUp();
this.hide();
};
ProjectDialogMorph.prototype.openProject = function () {
var proj = this.listField.selected,
src;
if (!proj) {return; }
this.ide.source = this.source;
if (this.source === 'cloud') {
this.openCloudProject(proj);
} else if (this.source === 'examples') {
// Note "file" is a property of the parseResourceFile function.
src = this.ide.getURL(this.ide.resourceURL('Examples', proj.fileName));
this.ide.openProjectString(src);
this.destroy();
} else { // 'local'
this.ide.source = null;
this.ide.openProject(proj.name);
this.destroy();
}
};
ProjectDialogMorph.prototype.openCloudProject = function (project, delta) {
var myself = this;
myself.ide.nextSteps([
function () {
myself.ide.showMessage('Fetching project\nfrom the cloud...');
},
function () {
myself.rawOpenCloudProject(project, delta);
}
]);
};
ProjectDialogMorph.prototype.rawOpenCloudProject = function (proj, delta) {
var myself = this;
this.ide.cloud.getProject(
proj.projectname,
delta,
function (clouddata) {
myself.ide.source = 'cloud';
myself.ide.nextSteps([
function () {
myself.ide.openCloudDataString(clouddata);
}
]);
location.hash = '';
if (proj.ispublic) {
location.hash = '#present:Username=' +
encodeURIComponent(myself.ide.cloud.username) +
'&ProjectName=' +
encodeURIComponent(proj.projectname);
}
},
myself.ide.cloudError()
);
this.destroy();
};
ProjectDialogMorph.prototype.saveProject = function () {
var name = this.nameField.contents().text.text,
notes = this.notesText.text,
myself = this;
this.ide.projectNotes = notes || this.ide.projectNotes;
if (name) {
if (this.source === 'cloud') {
if (detect(
this.projectList,
function (item) {return item.projectname === name; }
)) {
this.ide.confirm(
localize(
'Are you sure you want to replace'
) + '\n"' + name + '"?',
'Replace Project',
function () {
myself.ide.setProjectName(name);
myself.saveCloudProject();
}
);
} else {
this.ide.setProjectName(name);
myself.saveCloudProject();
}
} else if (this.source === 'disk') {
this.ide.exportProject(name, false);
this.ide.source = 'disk';
this.destroy();
}
}
};
ProjectDialogMorph.prototype.saveCloudProject = function () {
this.ide.source = 'cloud';
this.ide.saveProjectToCloud();
this.destroy();
};
ProjectDialogMorph.prototype.deleteProject = function () {
var myself = this,
proj,
idx,
name;
if (this.source === 'cloud') {
proj = this.listField.selected;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to delete'
) + '\n"' + proj.projectname + '"?',
'Delete Project',
function () {
myself.ide.cloud.deleteProject(
proj.projectname,
null, // username is implicit
function () {
myself.ide.hasChangedMedia = true;
idx = myself.projectList.indexOf(proj);
myself.projectList.splice(idx, 1);
myself.installCloudProjectList(
myself.projectList
); // refresh list
},
myself.ide.cloudError()
);
}
);
}
} else { // 'local, examples'
if (this.listField.selected) {
name = this.listField.selected.name;
this.ide.confirm(
localize(
'Are you sure you want to delete'
) + '\n"' + name + '"?',
'Delete Project',
function () {
delete localStorage['-snap-project-' + name];
myself.setSource(myself.source); // refresh list
}
);
}
}
};
ProjectDialogMorph.prototype.shareProject = function () {
var myself = this,
ide = this.ide,
proj = this.listField.selected,
entry = this.listField.active;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to share'
) + '\n"' + proj.projectname + '"?',
'Share Project',
function () {
ide.showMessage('sharing\nproject...');
ide.cloud.shareProject(
proj.projectname,
null, // username is implicit
function () {
proj.ispublic = true;
myself.unshareButton.show();
myself.shareButton.hide();
myself.publishButton.show();
myself.unpublishButton.hide();
entry.label.isBold = true;
entry.label.rerender();
myself.buttons.fixLayout();
myself.rerender();
myself.ide.showMessage('shared.', 2);
// Set the Shared URL if the project is currently open
if (proj.projectname === ide.projectName) {
var usr = ide.cloud.username,
projectId = 'Username=' +
encodeURIComponent(usr.toLowerCase()) +
'&ProjectName=' +
encodeURIComponent(proj.projectname);
location.hash = 'present:' + projectId;
}
},
myself.ide.cloudError()
);
}
);
}
};
ProjectDialogMorph.prototype.unshareProject = function () {
var myself = this,
ide = this.ide,
proj = this.listField.selected,
entry = this.listField.active;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to unshare'
) + '\n"' + proj.projectname + '"?',
'Unshare Project',
function () {
ide.showMessage('unsharing\nproject...');
ide.cloud.unshareProject(
proj.projectname,
null, // username is implicit
function () {
proj.ispublic = false;
myself.shareButton.show();
myself.unshareButton.hide();
myself.publishButton.hide();
myself.unpublishButton.hide();
entry.label.isBold = false;
entry.label.isItalic = false;
entry.label.rerender();
myself.buttons.fixLayout();
myself.rerender();
myself.ide.showMessage('unshared.', 2);
if (proj.projectname === ide.projectName) {
location.hash = '';
}
},
myself.ide.cloudError()
);
}
);
}
};
ProjectDialogMorph.prototype.publishProject = function () {
var myself = this,
ide = this.ide,
proj = this.listField.selected,
entry = this.listField.active;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to publish'
) + '\n"' + proj.projectname + '"?',
'Publish Project',
function () {
ide.showMessage('publishing\nproject...');
ide.cloud.publishProject(
proj.projectname,
null, // username is implicit
function () {
proj.ispublished = true;
myself.unshareButton.show();
myself.shareButton.hide();
myself.publishButton.hide();
myself.unpublishButton.show();
entry.label.isItalic = true;
entry.label.rerender();
myself.buttons.fixLayout();
myself.rerender();
myself.ide.showMessage('published.', 2);
// Set the Shared URL if the project is currently open
if (proj.projectname === ide.projectName) {
var usr = ide.cloud.username,
projectId = 'Username=' +
encodeURIComponent(usr.toLowerCase()) +
'&ProjectName=' +
encodeURIComponent(proj.projectname);
location.hash = 'present:' + projectId;
}
},
myself.ide.cloudError()
);
}
);
}
};
ProjectDialogMorph.prototype.unpublishProject = function () {
var myself = this,
proj = this.listField.selected,
entry = this.listField.active;
if (proj) {
this.ide.confirm(
localize(
'Are you sure you want to unpublish'
) + '\n"' + proj.projectname + '"?',
'Unpublish Project',
function () {
myself.ide.showMessage('unpublishing\nproject...');
myself.ide.cloud.unpublishProject(
proj.projectname,
null, // username is implicit
function () {
proj.ispublished = false;
myself.unshareButton.show();
myself.shareButton.hide();
myself.publishButton.show();
myself.unpublishButton.hide();
entry.label.isItalic = false;
entry.label.rerender();
myself.buttons.fixLayout();
myself.rerender();
myself.ide.showMessage('unpublished.', 2);
},
myself.ide.cloudError()
);
}
);
}
};
ProjectDialogMorph.prototype.edit = function () {
if (this.nameField) {
this.nameField.edit();
} else if (this.filterField) {
this.filterField.edit();
}
};
// ProjectDialogMorph layout
ProjectDialogMorph.prototype.fixLayout = function () {
var th = fontHeight(this.titleFontSize) + this.titlePadding * 2,
thin = this.padding / 2,
inputField = this.nameField || this.filterField;
if (this.buttons && (this.buttons.children.length > 0)) {
this.buttons.fixLayout();
}
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
th + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height() - this.padding * 3 - th - this.buttons.height()
));
this.srcBar.setPosition(this.body.position());
inputField.setWidth(
this.body.width() - this.srcBar.width() - this.padding * 6
);
inputField.setLeft(this.srcBar.right() + this.padding * 3);
inputField.setTop(this.srcBar.top());
this.listField.setLeft(this.srcBar.right() + this.padding);
this.listField.setWidth(
this.body.width()
- this.srcBar.width()
- this.preview.width()
- this.padding
- thin
);
this.listField.contents.children[0].adjustWidths();
this.listField.setTop(inputField.bottom() + this.padding);
this.listField.setHeight(
this.body.height() - inputField.height() - this.padding
);
if (this.magnifyingGlass) {
this.magnifyingGlass.setTop(inputField.top());
this.magnifyingGlass.setLeft(this.listField.left());
}
this.preview.setRight(this.body.right());
this.preview.setTop(inputField.bottom() + this.padding);
this.notesField.setTop(this.preview.bottom() + thin);
this.notesField.setLeft(this.preview.left());
this.notesField.setHeight(
this.body.bottom() - this.preview.bottom() - thin
);
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(this.top() + (th - this.label.height()) / 2);
}
if (this.buttons && (this.buttons.children.length > 0)) {
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// ProjectRecoveryDialogMorph /////////////////////////////////////////
// I show previous versions for a particular project and
// let users recover them.
ProjectRecoveryDialogMorph.prototype = new DialogBoxMorph();
ProjectRecoveryDialogMorph.prototype.constructor = ProjectRecoveryDialogMorph;
ProjectRecoveryDialogMorph.uber = DialogBoxMorph.prototype;
// ProjectRecoveryDialogMorph instance creation:
function ProjectRecoveryDialogMorph(ide, project, browser) {
this.init(ide, project, browser);
}
ProjectRecoveryDialogMorph.prototype.init = function (
ide,
projectName,
browser
) {
// initialize inherited properties:
ProjectRecoveryDialogMorph.uber.init.call(
this,
this, // target
null, // function
null // environment
);
this.ide = ide;
this.browser = browser;
this.key = 'recoverProject';
this.projectName = projectName;
this.versions = null;
this.handle = null;
this.listField = null;
this.preview = null;
this.notesText = null;
this.notesField = null;
this.labelString = 'Recover project';
this.createLabel();
this.buildContents();
};
ProjectRecoveryDialogMorph.prototype.buildContents = function () {
this.addBody(new Morph());
this.body.color = this.color;
this.buildListField();
this.preview = new Morph();
this.preview.fixLayout = nop;
this.preview.edge = InputFieldMorph.prototype.edge;
this.preview.fontSize = InputFieldMorph.prototype.fontSize;
this.preview.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.preview.contrast = InputFieldMorph.prototype.contrast;
this.preview.render = function (ctx) {
InputFieldMorph.prototype.render.call(this, ctx);
if (this.texture) {
this.renderTexture(this.texture, ctx);
}
};
this.preview.renderCachedTexture = function (ctx) {
ctx.drawImage(this.cachedTexture, this.edge, this.edge);
};
this.preview.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.preview.setExtent(
this.ide.serializer.thumbnailSize.add(this.preview.edge * 2)
);
this.body.add(this.preview);
this.notesField = new ScrollFrameMorph();
this.notesField.fixLayout = nop;
this.notesField.edge = InputFieldMorph.prototype.edge;
this.notesField.fontSize = InputFieldMorph.prototype.fontSize;
this.notesField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.notesField.contrast = InputFieldMorph.prototype.contrast;
this.notesField.render = InputFieldMorph.prototype.render;
this.notesField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.notesField.acceptsDrops = false;
this.notesField.contents.acceptsDrops = false;
this.notesText = new TextMorph('');
this.notesField.isTextLineWrapping = true;
this.notesField.padding = 3;
this.notesField.setContents(this.notesText);
this.notesField.setWidth(this.preview.width());
this.body.add(this.notesField);
this.addButton('recoverProject', 'Recover', true);
this.addButton('cancel', 'Cancel');
this.setExtent(new Point(360, 300));
this.fixLayout();
};
ProjectRecoveryDialogMorph.prototype.buildListField = function () {
var myself = this;
this.listField = new ListMorph([]);
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.listField.action = function (item) {
var version;
if (item === undefined) { return; }
version = detect(
myself.versions,
function (version) {
return version.lastupdated === item;
});
myself.notesText.text = version.notes || '';
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
myself.preview.texture = version.thumbnail;
myself.preview.cachedTexture = null;
myself.preview.rerender();
};
this.ide.cloud.getProjectVersionMetadata(
this.projectName,
function (versions) {
var today = new Date(),
yesterday = new Date();
yesterday.setDate(today.getDate() - 1);
myself.versions = versions;
myself.versions.forEach(function (version) {
var date = new Date(
new Date().getTime() - version.lastupdated * 1000
);
if (date.toDateString() === today.toDateString()) {
version.lastupdated = localize('Today, ') +
date.toLocaleTimeString();
} else if (date.toDateString() === yesterday.toDateString()) {
version.lastupdated = localize('Yesterday, ') +
date.toLocaleTimeString();
} else {
version.lastupdated = date.toLocaleString();
}
});
myself.listField.elements =
myself.versions.map(function (version) {
return version.lastupdated;
});
myself.clearDetails();
myself.listField.buildListContents();
myself.fixListFieldItemColors();
myself.listField.adjustScrollBars();
myself.listField.scrollY(myself.listField.top());
myself.fixLayout();
},
this.ide.cloudError()
);
this.body.add(this.listField);
};
ProjectRecoveryDialogMorph.prototype.cancel = function () {
var myself = this;
this.browser.show();
this.browser.listField.select(
detect(
this.browser.projectList,
function (item) {
return item.projectname === myself.projectName;
}
)
);
ProjectRecoveryDialogMorph.uber.cancel.call(this);
};
ProjectRecoveryDialogMorph.prototype.recoverProject = function () {
var lastupdated = this.listField.selected,
version = detect(
this.versions,
function (version) {
return version.lastupdated === lastupdated;
});
this.browser.openCloudProject(
{projectname: this.projectName},
version.delta
);
this.destroy();
};
ProjectRecoveryDialogMorph.prototype.popUp = function () {
var world = this.ide.world();
if (world) {
ProjectRecoveryDialogMorph.uber.popUp.call(this, world);
this.handle = new HandleMorph(
this,
300,
300,
this.corner,
this.corner
);
}
};
ProjectRecoveryDialogMorph.prototype.fixListFieldItemColors =
ProjectDialogMorph.prototype.fixListFieldItemColors;
ProjectRecoveryDialogMorph.prototype.clearDetails =
ProjectDialogMorph.prototype.clearDetails;
ProjectRecoveryDialogMorph.prototype.fixLayout = function () {
var titleHeight = fontHeight(this.titleFontSize) + this.titlePadding * 2,
thin = this.padding / 2;
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
titleHeight + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height()
- this.padding * 3 // top, bottom and button padding.
- titleHeight
- this.buttons.height()
));
this.listField.setWidth(
this.body.width()
- this.preview.width()
- this.padding
);
this.listField.contents.children[0].adjustWidths();
this.listField.setPosition(this.body.position());
this.listField.setHeight(this.body.height());
this.preview.setRight(this.body.right());
this.preview.setTop(this.listField.top());
this.notesField.setTop(this.preview.bottom() + thin);
this.notesField.setLeft(this.preview.left());
this.notesField.setHeight(
this.body.bottom() - this.preview.bottom() - thin
);
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(
this.top() + (titleHeight - this.label.height()) / 2
);
}
if (this.buttons) {
this.buttons.fixLayout();
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// LibraryImportDialogMorph ///////////////////////////////////////////
// I am preview dialog shown before importing a library.
// I inherit from a DialogMorph but look similar to
// ProjectDialogMorph, and BlockImportDialogMorph
LibraryImportDialogMorph.prototype = new DialogBoxMorph();
LibraryImportDialogMorph.prototype.constructor = LibraryImportDialogMorph;
LibraryImportDialogMorph.uber = DialogBoxMorph.prototype;
// LibraryImportDialogMorph instance creation:
function LibraryImportDialogMorph(ide, librariesData) {
this.init(ide, librariesData);
}
LibraryImportDialogMorph.prototype.init = function (ide, librariesData) {
// initialize inherited properties:
LibraryImportDialogMorph.uber.init.call(
this,
this, // target
null, // function
null // environment
);
this.ide = ide;
this.key = 'importLibrary';
this.librariesData = librariesData; // [{name: , fileName: , description:}]
// I contain a cached version of the libaries I have displayed,
// because users may choose to explore a library many times before
// importing.
this.libraryCache = {}; // {fileName: [blocks-array] }
this.handle = null;
this.listField = null;
this.palette = null;
this.notesText = null;
this.notesField = null;
this.labelString = 'Import library';
this.createLabel();
this.buildContents();
};
LibraryImportDialogMorph.prototype.buildContents = function () {
this.addBody(new Morph());
this.body.color = this.color;
this.initializePalette();
this.initializeLibraryDescription();
this.installLibrariesList();
this.addButton('importLibrary', 'Import');
this.addButton('cancel', 'Cancel');
this.setExtent(new Point(460, 455));
this.fixLayout();
};
LibraryImportDialogMorph.prototype.initializePalette = function () {
// I will display a scrolling list of blocks.
if (this.palette) {this.palette.destroy(); }
this.palette = new ScrollFrameMorph(
null,
null,
SpriteMorph.prototype.sliderColor
);
this.palette.color = SpriteMorph.prototype.paletteColor;
this.palette.padding = 4;
this.palette.isDraggable = false;
this.palette.acceptsDrops = false;
this.palette.contents.acceptsDrops = false;
this.body.add(this.palette);
};
LibraryImportDialogMorph.prototype.initializeLibraryDescription = function () {
if (this.notesField) {this.notesField.destroy(); }
this.notesField = new ScrollFrameMorph();
this.notesField.fixLayout = nop;
this.notesField.edge = InputFieldMorph.prototype.edge;
this.notesField.fontSize = InputFieldMorph.prototype.fontSize;
this.notesField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.notesField.contrast = InputFieldMorph.prototype.contrast;
this.notesField.render = InputFieldMorph.prototype.render;
this.notesField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.notesField.acceptsDrops = false;
this.notesField.contents.acceptsDrops = false;
this.notesText = new TextMorph('');
this.notesField.isTextLineWrapping = true;
this.notesField.padding = 3;
this.notesField.setContents(this.notesText);
this.notesField.setHeight(100);
this.body.add(this.notesField);
};
LibraryImportDialogMorph.prototype.installLibrariesList = function () {
var myself = this;
if (this.listField) {this.listField.destroy(); }
this.listField = new ListMorph(
this.librariesData,
function (element) {return element.name; },
null,
function () {myself.importLibrary(); }
);
this.fixListFieldItemColors();
this.listField.fixLayout = nop;
this.listField.edge = InputFieldMorph.prototype.edge;
this.listField.fontSize = InputFieldMorph.prototype.fontSize;
this.listField.typeInPadding = InputFieldMorph.prototype.typeInPadding;
this.listField.contrast = InputFieldMorph.prototype.contrast;
this.listField.render = InputFieldMorph.prototype.render;
this.listField.drawRectBorder = InputFieldMorph.prototype.drawRectBorder;
this.listField.action = function (item) {
if (isNil(item)) {return; }
myself.notesText.text = localize(item.description || '');
myself.notesText.rerender();
myself.notesField.contents.adjustBounds();
if (myself.hasCached(item.fileName)) {
myself.displayBlocks(item.fileName);
} else {
myself.showMessage(
localize('Loading') + '\n' + localize(item.name)
);
myself.ide.getURL(
myself.ide.resourceURL('libraries', item.fileName),
function(libraryXML) {
myself.cacheLibrary(
item.fileName,
myself.ide.serializer.loadBlocks(libraryXML)
);
myself.displayBlocks(item.fileName);
}
);
}
};
this.listField.setWidth(200);
this.body.add(this.listField);
this.fixLayout();
};
LibraryImportDialogMorph.prototype.popUp = function () {
var world = this.ide.world();
if (world) {
LibraryImportDialogMorph.uber.popUp.call(this, world);
this.handle = new HandleMorph(
this,
300,
300,
this.corner,
this.corner
);
}
};
LibraryImportDialogMorph.prototype.fixListFieldItemColors =
ProjectDialogMorph.prototype.fixListFieldItemColors;
LibraryImportDialogMorph.prototype.clearDetails =
ProjectDialogMorph.prototype.clearDetails;
LibraryImportDialogMorph.prototype.fixLayout = function () {
var titleHeight = fontHeight(this.titleFontSize) + this.titlePadding * 2,
thin = this.padding / 2;
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
titleHeight + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height()
- this.padding * 3 // top, bottom and button padding.
- titleHeight
- this.buttons.height()
));
this.listField.setExtent(new Point(
200,
this.body.height()
));
this.notesField.setExtent(new Point(
this.body.width() - this.listField.width() - thin,
100
));
this.palette.setExtent(new Point(
this.notesField.width(),
this.body.height() - this.notesField.height() - thin
));
this.listField.contents.children[0].adjustWidths();
this.listField.setPosition(this.body.position());
this.palette.setPosition(this.listField.topRight().add(
new Point(thin, 0)
));
this.notesField.setPosition(this.palette.bottomLeft().add(
new Point(0, thin)
));
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(
this.top() + (titleHeight - this.label.height()) / 2
);
}
if (this.buttons) {
this.buttons.fixLayout();
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// Library Cache Utilities.
LibraryImportDialogMorph.prototype.hasCached = function (key) {
return this.libraryCache.hasOwnProperty(key);
};
LibraryImportDialogMorph.prototype.cacheLibrary = function (key, blocks) {
this.libraryCache[key] = blocks ;
};
LibraryImportDialogMorph.prototype.cachedLibrary = function (key) {
return this.libraryCache[key];
};
LibraryImportDialogMorph.prototype.importLibrary = function () {
var blocks,
ide = this.ide,
selectedLibrary = this.listField.selected.fileName,
libraryName = this.listField.selected.name;
if (this.hasCached(selectedLibrary)) {
blocks = this.cachedLibrary(selectedLibrary);
blocks.forEach(function (def) {
def.receiver = ide.stage;
ide.stage.globalBlocks.push(def);
ide.stage.replaceDoubleDefinitionsFor(def);
});
ide.showMessage(localize('Imported') + ' ' + localize(libraryName), 2);
} else {
ide.showMessage(localize('Loading') + ' ' + localize(libraryName));
ide.getURL(
ide.resourceURL('libraries', selectedLibrary),
function(libraryText) {
ide.droppedText(libraryText, libraryName);
}
);
}
this.destroy();
};
LibraryImportDialogMorph.prototype.displayBlocks = function (libraryKey) {
var x, y, blockImage, previousCategory, blockContainer,
myself = this,
padding = 4,
blocksList = this.cachedLibrary(libraryKey);
if (!blocksList.length) {return; }
// populate palette, grouped by categories.
this.initializePalette();
x = this.palette.left() + padding;
y = this.palette.top();
SpriteMorph.prototype.categories.forEach(function (category) {
blocksList.forEach(function (definition) {
if (definition.category !== category) {return; }
if (category !== previousCategory) {
y += padding;
}
previousCategory = category;
blockImage = definition.templateInstance().fullImage();
blockContainer = new Morph();
blockContainer.isCachingImage = true;
blockContainer.setExtent(
new Point(blockImage.width, blockImage.height)
);
blockContainer.cachedImage = blockImage;
blockContainer.setPosition(new Point(x, y));
myself.palette.addContents(blockContainer);
y += blockContainer.fullBounds().height() + padding;
});
});
this.palette.scrollX(padding);
this.palette.scrollY(padding);
this.fixLayout();
};
LibraryImportDialogMorph.prototype.showMessage = function (msgText) {
var msg = new MenuMorph(null, msgText);
this.initializePalette();
this.fixLayout();
msg.popUpCenteredInWorld(this.palette.contents);
};
// SpriteIconMorph ////////////////////////////////////////////////////
/*
I am a selectable element in the Sprite corral, keeping a self-updating
thumbnail of the sprite I'm respresenting, and a self-updating label
of the sprite's name (in case it is changed elsewhere)
*/
// SpriteIconMorph inherits from ToggleButtonMorph (Widgets)
SpriteIconMorph.prototype = new ToggleButtonMorph();
SpriteIconMorph.prototype.constructor = SpriteIconMorph;
SpriteIconMorph.uber = ToggleButtonMorph.prototype;
// SpriteIconMorph settings
SpriteIconMorph.prototype.thumbSize = new Point(40, 40);
SpriteIconMorph.prototype.labelShadowOffset = null;
SpriteIconMorph.prototype.labelShadowColor = null;
SpriteIconMorph.prototype.labelColor = new Color(255, 255, 255);
SpriteIconMorph.prototype.fontSize = 9;
// SpriteIconMorph instance creation:
function SpriteIconMorph(aSprite) {
this.init(aSprite);
}
SpriteIconMorph.prototype.init = function (aSprite) {
var colors, action, query, hover, myself = this;
colors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor
];
action = function () {
// make my sprite the current one
var ide = myself.parentThatIsA(IDE_Morph);
if (ide) {
ide.selectSprite(myself.object);
}
};
query = function () {
// answer true if my sprite is the current one
var ide = myself.parentThatIsA(IDE_Morph);
if (ide) {
return ide.currentSprite === myself.object;
}
return false;
};
hover = function () {
if (!aSprite.exemplar) {return null; }
return (localize('parent') + ':\n' + aSprite.exemplar.name);
};
// additional properties:
this.object = aSprite || new SpriteMorph(); // mandatory, actually
this.version = this.object.version;
this.thumbnail = null;
this.rotationButton = null; // synchronous rotation of nested sprites
// initialize inherited properties:
SpriteIconMorph.uber.init.call(
this,
colors, // color overrides, <array>: [normal, highlight, pressed]
null, // target - not needed here
action, // a toggle function
this.object.name, // label string
query, // predicate/selector
null, // environment
hover // hint
);
// override defaults and build additional components
this.isDraggable = true;
this.createThumbnail();
this.padding = 2;
this.corner = 8;
this.fixLayout();
this.fps = 1;
};
SpriteIconMorph.prototype.createThumbnail = function () {
if (this.thumbnail) {
this.thumbnail.destroy();
}
this.thumbnail = new Morph();
this.thumbnail.isCachingImage = true;
this.thumbnail.bounds.setExtent(this.thumbSize);
if (this.object instanceof SpriteMorph) { // support nested sprites
this.thumbnail.cachedImage = this.object.fullThumbnail(
this.thumbSize,
this.thumbnail.cachedImage
);
this.add(this.thumbnail);
this.createRotationButton();
} else {
this.thumbnail.cachedImage = this.object.thumbnail(
this.thumbSize,
this.thumbnail.cachedImage
);
this.add(this.thumbnail);
}
};
SpriteIconMorph.prototype.createLabel = function () {
var txt;
if (this.label) {
this.label.destroy();
}
txt = new StringMorph(
this.object.name,
this.fontSize,
this.fontStyle,
true,
false,
false,
this.labelShadowOffset,
this.labelShadowColor,
this.labelColor
);
this.label = new FrameMorph();
this.label.acceptsDrops = false;
this.label.alpha = 0;
this.label.setExtent(txt.extent());
txt.setPosition(this.label.position());
this.label.add(txt);
this.add(this.label);
};
SpriteIconMorph.prototype.createRotationButton = function () {
var button, myself = this;
if (this.rotationButton) {
this.rotationButton.destroy();
this.roationButton = null;
}
if (!this.object.anchor) {
return;
}
button = new ToggleButtonMorph(
null, // colors,
null, // target
function () {
myself.object.rotatesWithAnchor =
!myself.object.rotatesWithAnchor;
},
[
'\u2192',
'\u21BB'
],
function () { // query
return myself.object.rotatesWithAnchor;
}
);
button.corner = 8;
button.labelMinExtent = new Point(11, 11);
button.padding = 0;
button.pressColor = button.color;
// button.hint = 'rotate synchronously\nwith anchor';
button.fixLayout();
button.refresh();
this.rotationButton = button;
this.add(this.rotationButton);
};
// SpriteIconMorph stepping
SpriteIconMorph.prototype.step = function () {
if (this.version !== this.object.version) {
this.createThumbnail();
this.createLabel();
this.fixLayout();
this.version = this.object.version;
this.refresh();
}
};
// SpriteIconMorph layout
SpriteIconMorph.prototype.fixLayout = function () {
if (!this.thumbnail || !this.label) {return null; }
this.bounds.setWidth(
this.thumbnail.width()
+ this.outline * 2
+ this.edge * 2
+ this.padding * 2
);
this.bounds.setHeight(
this.thumbnail.height()
+ this.outline * 2
+ this.edge * 2
+ this.padding * 3
+ this.label.height()
);
this.thumbnail.setCenter(this.center());
this.thumbnail.setTop(
this.top() + this.outline + this.edge + this.padding
);
if (this.rotationButton) {
this.rotationButton.setTop(this.top());
this.rotationButton.setRight(this.right());
}
this.label.setWidth(
Math.min(
this.label.children[0].width(), // the actual text
this.thumbnail.width()
)
);
this.label.setCenter(this.center());
this.label.setTop(
this.thumbnail.bottom() + this.padding
);
};
// SpriteIconMorph menu
SpriteIconMorph.prototype.userMenu = function () {
var menu = new MenuMorph(this),
myself = this;
if (this.object instanceof StageMorph) {
menu.addItem(
'pic...',
function () {
var ide = myself.parentThatIsA(IDE_Morph);
ide.saveCanvasAs(
myself.object.fullImage(),
this.object.name
);
},
'open a new window\nwith a picture of the stage'
);
if (this.object.trailsLog.length) {
menu.addItem(
'svg...',
function () {myself.object.exportTrailsLogAsSVG(); },
'export pen trails\nline segments as SVG'
);
}
return menu;
}
if (!(this.object instanceof SpriteMorph)) {return null; }
menu.addItem("show", 'showSpriteOnStage');
menu.addLine();
menu.addItem("duplicate", 'duplicateSprite');
if (StageMorph.prototype.enableInheritance) {
menu.addItem("clone", 'instantiateSprite');
}
menu.addItem("delete", 'removeSprite');
menu.addLine();
if (StageMorph.prototype.enableInheritance) {
/* version that hides refactoring capability unless shift-clicked
if (this.world().currentKey === 16) { // shift-clicked
menu.addItem(
"parent...",
'chooseExemplar',
null,
new Color(100, 0, 0)
);
}
*/
menu.addItem("parent...", 'chooseExemplar');
if (this.object.exemplar) {
menu.addItem(
"release",
'releaseSprite',
'make temporary and\nhide in the sprite corral'
);
}
}
if (this.object.anchor) {
menu.addItem(
localize('detach from') + ' ' + this.object.anchor.name,
function () {myself.object.detachFromAnchor(); }
);
}
if (this.object.parts.length) {
menu.addItem(
'detach all parts',
function () {myself.object.detachAllParts(); }
);
}
menu.addItem("export...", 'exportSprite');
return menu;
};
SpriteIconMorph.prototype.duplicateSprite = function () {
var ide = this.parentThatIsA(IDE_Morph);
if (ide) {
ide.duplicateSprite(this.object);
}
};
SpriteIconMorph.prototype.instantiateSprite = function () {
var ide = this.parentThatIsA(IDE_Morph);
if (ide) {
ide.instantiateSprite(this.object);
}
};
SpriteIconMorph.prototype.removeSprite = function () {
var ide = this.parentThatIsA(IDE_Morph);
if (ide) {
ide.removeSprite(this.object);
}
};
SpriteIconMorph.prototype.exportSprite = function () {
this.object.exportSprite();
};
SpriteIconMorph.prototype.chooseExemplar = function () {
this.object.chooseExemplar();
};
SpriteIconMorph.prototype.releaseSprite = function () {
this.object.release();
};
SpriteIconMorph.prototype.showSpriteOnStage = function () {
this.object.showOnStage();
};
// SpriteIconMorph events
SpriteIconMorph.prototype.mouseDoubleClick = function () {
if (this.object instanceof SpriteMorph) {
this.object.flash();
}
};
// SpriteIconMorph drawing
SpriteIconMorph.prototype.render = function (ctx) {
// only draw the edges if I am selected
switch (this.userState) {
case 'highlight':
this.drawBackground(ctx, this.highlightColor);
break;
case 'pressed':
this.drawOutline(ctx);
this.drawBackground(ctx, this.pressColor);
this.drawEdges(
ctx,
this.pressColor,
this.pressColor.lighter(40),
this.pressColor.darker(40)
);
break;
default:
this.drawBackground(ctx, this.color);
}
};
// SpriteIconMorph drag & drop
SpriteIconMorph.prototype.prepareToBeGrabbed = function () {
var ide = this.parentThatIsA(IDE_Morph),
idx;
this.mouseClickLeft(); // select me
this.alpha = 0.5;
if (ide) {
idx = ide.sprites.asArray().indexOf(this.object);
ide.sprites.remove(idx + 1);
ide.createCorral();
ide.fixLayout();
}
};
SpriteIconMorph.prototype.justDropped = function () {
this.alpha = 1;
};
SpriteIconMorph.prototype.wantsDropOf = function (morph) {
// allow scripts & media to be copied from one sprite to another
// by drag & drop
return morph instanceof BlockMorph
|| (morph instanceof CostumeIconMorph)
|| (morph instanceof SoundIconMorph);
};
SpriteIconMorph.prototype.reactToDropOf = function (morph, hand) {
if (morph instanceof BlockMorph) {
this.copyStack(morph);
} else if (morph instanceof CostumeIconMorph) {
this.copyCostume(morph.object);
} else if (morph instanceof SoundIconMorph) {
this.copySound(morph.object);
}
this.world().add(morph);
morph.slideBackTo(hand.grabOrigin);
};
SpriteIconMorph.prototype.copyStack = function (block) {
var sprite = this.object,
dup = block.fullCopy(),
y = Math.max(sprite.scripts.children.map(function (stack) {
return stack.fullBounds().bottom();
}).concat([sprite.scripts.top()]));
dup.setPosition(new Point(sprite.scripts.left() + 20, y + 20));
sprite.scripts.add(dup);
dup.allComments().forEach(function (comment) {
comment.align(dup);
});
sprite.scripts.adjustBounds();
// delete all local custom blocks (methods) that the receiver
// doesn't understand
dup.allChildren().forEach(function (morph) {
if (morph.isCustomBlock &&
!morph.isGlobal &&
!sprite.getMethod(morph.blockSpec)
) {
morph.deleteBlock();
}
});
};
SpriteIconMorph.prototype.copyCostume = function (costume) {
var dup = costume.copy();
dup.name = this.object.newCostumeName(dup.name);
this.object.addCostume(dup);
this.object.wearCostume(dup);
};
SpriteIconMorph.prototype.copySound = function (sound) {
var dup = sound.copy();
this.object.addSound(dup.audio, dup.name);
};
// CostumeIconMorph ////////////////////////////////////////////////////
/*
I am a selectable element in the SpriteEditor's "Costumes" tab, keeping
a self-updating thumbnail of the costume I'm respresenting, and a
self-updating label of the costume's name (in case it is changed
elsewhere)
*/
// CostumeIconMorph inherits from ToggleButtonMorph (Widgets)
// ... and copies methods from SpriteIconMorph
CostumeIconMorph.prototype = new ToggleButtonMorph();
CostumeIconMorph.prototype.constructor = CostumeIconMorph;
CostumeIconMorph.uber = ToggleButtonMorph.prototype;
// CostumeIconMorph settings
CostumeIconMorph.prototype.thumbSize = new Point(80, 60);
CostumeIconMorph.prototype.labelShadowOffset = null;
CostumeIconMorph.prototype.labelShadowColor = null;
CostumeIconMorph.prototype.labelColor = new Color(255, 255, 255);
CostumeIconMorph.prototype.fontSize = 9;
// CostumeIconMorph instance creation:
function CostumeIconMorph(aCostume) {
this.init(aCostume);
}
CostumeIconMorph.prototype.init = function (aCostume) {
var colors, action, query, myself = this;
colors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor
];
action = function () {
// make my costume the current one
var ide = myself.parentThatIsA(IDE_Morph),
wardrobe = myself.parentThatIsA(WardrobeMorph);
if (ide) {
ide.currentSprite.wearCostume(myself.object);
}
if (wardrobe) {
wardrobe.updateSelection();
}
};
query = function () {
// answer true if my costume is the current one
var ide = myself.parentThatIsA(IDE_Morph);
if (ide) {
return ide.currentSprite.costume === myself.object;
}
return false;
};
// additional properties:
this.object = aCostume || new Costume(); // mandatory, actually
this.version = this.object.version;
this.thumbnail = null;
// initialize inherited properties:
CostumeIconMorph.uber.init.call(
this,
colors, // color overrides, <array>: [normal, highlight, pressed]
null, // target - not needed here
action, // a toggle function
this.object.name, // label string
query, // predicate/selector
null, // environment
null // hint
);
// override defaults and build additional components
this.isDraggable = true;
this.createThumbnail();
this.padding = 2;
this.corner = 8;
this.fixLayout();
this.fps = 1;
};
CostumeIconMorph.prototype.createThumbnail = function () {
var txt;
SpriteIconMorph.prototype.createThumbnail.call(this);
if (this.object instanceof SVG_Costume) {
txt = new StringMorph(
'svg',
this.fontSize * 0.8,
this.fontStyle,
false,
false,
false,
this.labelShadowOffset,
this.labelShadowColor,
this.labelColor
);
txt.setBottom(this.thumbnail.bottom());
this.thumbnail.add(txt);
}
};
CostumeIconMorph.prototype.createLabel
= SpriteIconMorph.prototype.createLabel;
// CostumeIconMorph stepping
CostumeIconMorph.prototype.step
= SpriteIconMorph.prototype.step;
// CostumeIconMorph layout
CostumeIconMorph.prototype.fixLayout
= SpriteIconMorph.prototype.fixLayout;
// CostumeIconMorph menu
CostumeIconMorph.prototype.userMenu = function () {
var menu = new MenuMorph(this);
if (!(this.object instanceof Costume)) {return null; }
menu.addItem("edit", "editCostume");
if (this.world().currentKey === 16) { // shift clicked
menu.addItem(
'edit rotation point only...',
'editRotationPointOnly',
null,
new Color(100, 0, 0)
);
}
menu.addItem("rename", "renameCostume");
menu.addLine();
menu.addItem("duplicate", "duplicateCostume");
menu.addItem("delete", "removeCostume");
menu.addLine();
menu.addItem("export", "exportCostume");
return menu;
};
CostumeIconMorph.prototype.editCostume = function () {
this.disinherit();
if (this.object instanceof SVG_Costume && this.object.shapes.length === 0) {
try {
this.object.parseShapes();
} catch (e) {
this.editRotationPointOnly();
return;
}
}
this.object.edit(
this.world(),
this.parentThatIsA(IDE_Morph),
false // not a new costume, retain existing rotation center
);
};
CostumeIconMorph.prototype.editRotationPointOnly = function () {
var ide = this.parentThatIsA(IDE_Morph);
this.object.editRotationPointOnly(this.world());
ide.hasChangedMedia = true;
};
CostumeIconMorph.prototype.renameCostume = function () {
this.disinherit();
var costume = this.object,
wardrobe = this.parentThatIsA(WardrobeMorph),
ide = this.parentThatIsA(IDE_Morph);
new DialogBoxMorph(
null,
function (answer) {
if (answer && (answer !== costume.name)) {
costume.name = wardrobe.sprite.newCostumeName(
answer,
costume
);
costume.version = Date.now();
ide.hasChangedMedia = true;
}
}
).prompt(
this.currentSprite instanceof SpriteMorph ?
'rename costume' : 'rename background',
costume.name,
this.world()
);
};
CostumeIconMorph.prototype.duplicateCostume = function () {
var wardrobe = this.parentThatIsA(WardrobeMorph),
ide = this.parentThatIsA(IDE_Morph),
newcos = this.object.copy();
newcos.name = wardrobe.sprite.newCostumeName(newcos.name);
wardrobe.sprite.addCostume(newcos);
wardrobe.updateList();
if (ide) {
ide.currentSprite.wearCostume(newcos);
}
};
CostumeIconMorph.prototype.removeCostume = function () {
var wardrobe = this.parentThatIsA(WardrobeMorph),
idx = this.parent.children.indexOf(this),
off = CamSnapshotDialogMorph.prototype.enableCamera ? 3 : 2,
ide = this.parentThatIsA(IDE_Morph);
wardrobe.removeCostumeAt(idx - off); // ignore paintbrush and camera buttons
if (ide.currentSprite.costume === this.object) {
ide.currentSprite.wearCostume(null);
}
};
CostumeIconMorph.prototype.exportCostume = function () {
var ide = this.parentThatIsA(IDE_Morph);
if (this.object instanceof SVG_Costume) {
// don't show SVG costumes in a new tab (shows text)
ide.saveFileAs(this.object.contents.src, 'text/svg', this.object.name);
} else { // rasterized Costume
ide.saveCanvasAs(this.object.contents, this.object.name);
}
};
// CostumeIconMorph drawing
CostumeIconMorph.prototype.render
= SpriteIconMorph.prototype.render;
// CostumeIconMorph inheritance
CostumeIconMorph.prototype.disinherit = function () {
var wardrobe = this.parentThatIsA(WardrobeMorph),
idx = this.parent.children.indexOf(this);
if (wardrobe.sprite.inheritsAttribute('costumes')) {
wardrobe.sprite.shadowAttribute('costumes');
this.object = wardrobe.sprite.costumes.at(idx - 3);
}
};
// CostumeIconMorph drag & drop
CostumeIconMorph.prototype.prepareToBeGrabbed = function () {
this.disinherit();
this.mouseClickLeft(); // select me
this.removeCostume();
};
// TurtleIconMorph ////////////////////////////////////////////////////
/*
I am a selectable element in the SpriteEditor's "Costumes" tab, keeping
a thumbnail of the sprite's or stage's default "Turtle" costume.
*/
// TurtleIconMorph inherits from ToggleButtonMorph (Widgets)
// ... and copies methods from SpriteIconMorph
TurtleIconMorph.prototype = new ToggleButtonMorph();
TurtleIconMorph.prototype.constructor = TurtleIconMorph;
TurtleIconMorph.uber = ToggleButtonMorph.prototype;
// TurtleIconMorph settings
TurtleIconMorph.prototype.thumbSize = new Point(80, 60);
TurtleIconMorph.prototype.labelShadowOffset = null;
TurtleIconMorph.prototype.labelShadowColor = null;
TurtleIconMorph.prototype.labelColor = new Color(255, 255, 255);
TurtleIconMorph.prototype.fontSize = 9;
// TurtleIconMorph instance creation:
function TurtleIconMorph(aSpriteOrStage) {
this.init(aSpriteOrStage);
}
TurtleIconMorph.prototype.init = function (aSpriteOrStage) {
var colors, action, query, myself = this;
colors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor
];
action = function () {
// make my costume the current one
var ide = myself.parentThatIsA(IDE_Morph),
wardrobe = myself.parentThatIsA(WardrobeMorph);
if (ide) {
ide.currentSprite.wearCostume(null);
}
if (wardrobe) {
wardrobe.updateSelection();
}
};
query = function () {
// answer true if my costume is the current one
var ide = myself.parentThatIsA(IDE_Morph);
if (ide) {
return ide.currentSprite.costume === null;
}
return false;
};
// additional properties:
this.object = aSpriteOrStage; // mandatory, actually
this.version = this.object.version;
this.thumbnail = null;
// initialize inherited properties:
TurtleIconMorph.uber.init.call(
this,
colors, // color overrides, <array>: [normal, highlight, pressed]
null, // target - not needed here
action, // a toggle function
'default', // label string
query, // predicate/selector
null, // environment
null // hint
);
// override defaults and build additional components
this.isDraggable = false;
this.createThumbnail();
this.padding = 2;
this.corner = 8;
this.fixLayout();
};
TurtleIconMorph.prototype.createThumbnail = function () {
var isFlat = MorphicPreferences.isFlat;
if (this.thumbnail) {
this.thumbnail.destroy();
}
if (this.object instanceof SpriteMorph) {
this.thumbnail = new SymbolMorph(
'turtle',
this.thumbSize.y,
this.labelColor,
isFlat ? null : new Point(-1, -1),
new Color(0, 0, 0)
);
} else {
this.thumbnail = new SymbolMorph(
'stage',
this.thumbSize.y,
this.labelColor,
isFlat ? null : new Point(-1, -1),
new Color(0, 0, 0)
);
}
this.add(this.thumbnail);
};
TurtleIconMorph.prototype.createLabel = function () {
var txt;
if (this.label) {
this.label.destroy();
}
txt = new StringMorph(
localize(
this.object instanceof SpriteMorph ? 'Turtle' : 'Empty'
),
this.fontSize,
this.fontStyle,
true,
false,
false,
this.labelShadowOffset,
this.labelShadowColor,
this.labelColor
);
this.label = new FrameMorph();
this.label.acceptsDrops = false;
this.label.alpha = 0;
this.label.setExtent(txt.extent());
txt.setPosition(this.label.position());
this.label.add(txt);
this.add(this.label);
};
// TurtleIconMorph layout
TurtleIconMorph.prototype.fixLayout
= SpriteIconMorph.prototype.fixLayout;
// TurtleIconMorph drawing
TurtleIconMorph.prototype.render
= SpriteIconMorph.prototype.render;
// TurtleIconMorph user menu
TurtleIconMorph.prototype.userMenu = function () {
var myself = this,
menu = new MenuMorph(this, 'pen'),
on = '\u25CF',
off = '\u25CB';
if (this.object instanceof StageMorph) {
return null;
}
menu.addItem(
(this.object.penPoint === 'tip' ? on : off) + ' ' + localize('tip'),
function () {
myself.object.penPoint = 'tip';
myself.object.changed();
myself.object.fixLayout();
myself.object.rerender();
}
);
menu.addItem(
(this.object.penPoint === 'middle' ? on : off) + ' ' + localize(
'middle'
),
function () {
myself.object.penPoint = 'middle';
myself.object.changed();
myself.object.fixLayout();
myself.object.rerender();
}
);
return menu;
};
// WardrobeMorph ///////////////////////////////////////////////////////
// I am a watcher on a sprite's costume list
// WardrobeMorph inherits from ScrollFrameMorph
WardrobeMorph.prototype = new ScrollFrameMorph();
WardrobeMorph.prototype.constructor = WardrobeMorph;
WardrobeMorph.uber = ScrollFrameMorph.prototype;
// WardrobeMorph settings
// ... to follow ...
// WardrobeMorph instance creation:
function WardrobeMorph(aSprite, sliderColor) {
this.init(aSprite, sliderColor);
}
WardrobeMorph.prototype.init = function (aSprite, sliderColor) {
// additional properties
this.sprite = aSprite || new SpriteMorph();
this.costumesVersion = null;
this.spriteVersion = null;
// initialize inherited properties
WardrobeMorph.uber.init.call(this, null, null, sliderColor);
// configure inherited properties
this.fps = 2;
this.updateList();
};
// Wardrobe updating
WardrobeMorph.prototype.updateList = function () {
var myself = this,
x = this.left() + 5,
y = this.top() + 5,
padding = 4,
toolsPadding = 5,
oldPos = this.contents.position(),
icon,
txt,
paintbutton,
cambutton;
this.changed();
this.contents.destroy();
this.contents = new FrameMorph(this);
this.contents.acceptsDrops = false;
this.contents.reactToDropOf = function (icon) {
myself.reactToDropOf(icon);
};
this.addBack(this.contents);
icon = new TurtleIconMorph(this.sprite);
icon.setPosition(new Point(x, y));
myself.addContents(icon);
y = icon.bottom() + padding;
paintbutton = new PushButtonMorph(
this,
"paintNew",
new SymbolMorph("brush", 15)
);
paintbutton.padding = 0;
paintbutton.corner = 12;
paintbutton.color = IDE_Morph.prototype.groupColor;
paintbutton.highlightColor = IDE_Morph.prototype.frameColor.darker(50);
paintbutton.pressColor = paintbutton.highlightColor;
paintbutton.labelMinExtent = new Point(36, 18);
paintbutton.labelShadowOffset = new Point(-1, -1);
paintbutton.labelShadowColor = paintbutton.highlightColor;
paintbutton.labelColor = TurtleIconMorph.prototype.labelColor;
paintbutton.contrast = this.buttonContrast;
paintbutton.hint = "Paint a new costume";
paintbutton.setPosition(new Point(x, y));
paintbutton.fixLayout();
paintbutton.setCenter(icon.center());
paintbutton.setLeft(icon.right() + padding * 4);
this.addContents(paintbutton);
if (CamSnapshotDialogMorph.prototype.enableCamera) {
cambutton = new PushButtonMorph(
this,
"newFromCam",
new SymbolMorph("camera", 15)
);
cambutton.padding = 0;
cambutton.corner = 12;
cambutton.color = IDE_Morph.prototype.groupColor;
cambutton.highlightColor = IDE_Morph.prototype.frameColor.darker(50);
cambutton.pressColor = paintbutton.highlightColor;
cambutton.labelMinExtent = new Point(36, 18);
cambutton.labelShadowOffset = new Point(-1, -1);
cambutton.labelShadowColor = paintbutton.highlightColor;
cambutton.labelColor = TurtleIconMorph.prototype.labelColor;
cambutton.contrast = this.buttonContrast;
cambutton.hint = "Import a new costume from your webcam";
cambutton.setPosition(new Point(x, y));
cambutton.fixLayout();
cambutton.setCenter(paintbutton.center());
cambutton.setLeft(paintbutton.right() + toolsPadding);
this.addContents(cambutton);
if (!CamSnapshotDialogMorph.prototype.enabled) {
cambutton.disable();
cambutton.hint =
CamSnapshotDialogMorph.prototype.notSupportedMessage;
}
document.addEventListener(
'cameraDisabled',
function () {
cambutton.disable();
cambutton.hint =
CamSnapshotDialogMorph.prototype.notSupportedMessage;
}
);
}
txt = new TextMorph(localize(
"costumes tab help" // look up long string in translator
));
txt.fontSize = 9;
txt.setColor(SpriteMorph.prototype.paletteTextColor);
txt.setPosition(new Point(x, y));
this.addContents(txt);
y = txt.bottom() + padding;
this.sprite.costumes.asArray().forEach(function (costume) {
icon = new CostumeIconMorph(costume);
icon.setPosition(new Point(x, y));
myself.addContents(icon);
y = icon.bottom() + padding;
});
this.costumesVersion = this.sprite.costumes.lastChanged;
this.contents.setPosition(oldPos);
this.adjustScrollBars();
this.changed();
this.updateSelection();
};
WardrobeMorph.prototype.updateSelection = function () {
this.contents.children.forEach(function (morph) {
if (morph.refresh) {morph.refresh(); }
});
this.spriteVersion = this.sprite.version;
};
// Wardrobe stepping
WardrobeMorph.prototype.step = function () {
if (this.costumesVersion !== this.sprite.costumes.lastChanged) {
this.updateList();
}
if (this.spriteVersion !== this.sprite.version) {
this.updateSelection();
}
};
// Wardrobe ops
WardrobeMorph.prototype.removeCostumeAt = function (idx) {
this.sprite.shadowAttribute('costumes');
this.sprite.costumes.remove(idx);
this.updateList();
};
WardrobeMorph.prototype.paintNew = function () {
var cos = new Costume(
newCanvas(null, true),
this.sprite.newCostumeName(localize('Untitled'))
),
ide = this.parentThatIsA(IDE_Morph),
myself = this;
cos.edit(this.world(), ide, true, null, function () {
myself.sprite.shadowAttribute('costumes');
myself.sprite.addCostume(cos);
myself.updateList();
if (ide) {
ide.currentSprite.wearCostume(cos);
}
});
};
WardrobeMorph.prototype.newFromCam = function () {
var camDialog,
ide = this.parentThatIsA(IDE_Morph),
myself = this,
sprite = this.sprite;
camDialog = new CamSnapshotDialogMorph(
ide,
sprite,
nop,
function (costume) {
sprite.addCostume(costume);
sprite.wearCostume(costume);
myself.updateList();
});
camDialog.key = 'camera';
camDialog.popUp(this.world());
};
// Wardrobe drag & drop
WardrobeMorph.prototype.wantsDropOf = function (morph) {
return morph instanceof CostumeIconMorph;
};
WardrobeMorph.prototype.reactToDropOf = function (icon) {
var idx = 0,
costume = icon.object,
top = icon.top();
icon.destroy();
this.contents.children.forEach(function (item) {
if (item instanceof CostumeIconMorph && item.top() < top - 4) {
idx += 1;
}
});
this.sprite.shadowAttribute('costumes');
this.sprite.costumes.add(costume, idx + 1);
this.updateList();
icon.mouseClickLeft(); // select
};
// SoundIconMorph ///////////////////////////////////////////////////////
/*
I am an element in the SpriteEditor's "Sounds" tab.
*/
// SoundIconMorph inherits from ToggleButtonMorph (Widgets)
// ... and copies methods from SpriteIconMorph
SoundIconMorph.prototype = new ToggleButtonMorph();
SoundIconMorph.prototype.constructor = SoundIconMorph;
SoundIconMorph.uber = ToggleButtonMorph.prototype;
// SoundIconMorph settings
SoundIconMorph.prototype.thumbSize = new Point(80, 60);
SoundIconMorph.prototype.labelShadowOffset = null;
SoundIconMorph.prototype.labelShadowColor = null;
SoundIconMorph.prototype.labelColor = new Color(255, 255, 255);
SoundIconMorph.prototype.fontSize = 9;
// SoundIconMorph instance creation:
function SoundIconMorph(aSound) {
this.init(aSound);
}
SoundIconMorph.prototype.init = function (aSound) {
var colors, action, query;
colors = [
IDE_Morph.prototype.groupColor,
IDE_Morph.prototype.frameColor,
IDE_Morph.prototype.frameColor
];
action = function () {
nop(); // When I am selected (which is never the case for sounds)
};
query = function () {
return false;
};
// additional properties:
this.object = aSound; // mandatory, actually
this.version = this.object.version;
this.thumbnail = null;
// initialize inherited properties:
SoundIconMorph.uber.init.call(
this,
colors, // color overrides, <array>: [normal, highlight, pressed]
null, // target - not needed here
action, // a toggle function
this.object.name, // label string
query, // predicate/selector
null, // environment
null // hint
);
// override defaults and build additional components
this.isDraggable = true;
this.createThumbnail();
this.padding = 2;
this.corner = 8;
this.fixLayout();
this.fps = 1;
};
SoundIconMorph.prototype.createThumbnail = function () {
var label;
if (this.thumbnail) {
this.thumbnail.destroy();
}
this.thumbnail = new Morph();
this.thumbnail.bounds.setExtent(this.thumbSize);
this.add(this.thumbnail);
label = new StringMorph(
this.createInfo(),
'16',
'',
true,
false,
false,
this.labelShadowOffset,
this.labelShadowColor,
new Color(200, 200, 200)
);
this.thumbnail.add(label);
label.setCenter(new Point(40, 15));
this.button = new PushButtonMorph(
this,
'toggleAudioPlaying',
(this.object.previewAudio ? 'Stop' : 'Play')
);
this.button.hint = 'Play sound';
this.button.fixLayout();
this.thumbnail.add(this.button);
this.button.setCenter(new Point(40, 40));
};
SoundIconMorph.prototype.createInfo = function () {
var dur = Math.round(this.object.audio.duration || 0),
mod = dur % 60;
return Math.floor(dur / 60).toString()
+ ":"
+ (mod < 10 ? "0" : "")
+ mod.toString();
};
SoundIconMorph.prototype.toggleAudioPlaying = function () {
var myself = this;
if (!this.object.previewAudio) {
//Audio is not playing
this.button.labelString = 'Stop';
this.button.hint = 'Stop sound';
this.object.previewAudio = this.object.play();
this.object.previewAudio.addEventListener('ended', function () {
myself.audioHasEnded();
}, false);
} else {
//Audio is currently playing
this.button.labelString = 'Play';
this.button.hint = 'Play sound';
this.object.previewAudio.pause();
this.object.previewAudio.terminated = true;
this.object.previewAudio = null;
}
this.button.createLabel();
};
SoundIconMorph.prototype.audioHasEnded = function () {
this.button.trigger();
this.button.mouseLeave();
};
SoundIconMorph.prototype.createLabel
= SpriteIconMorph.prototype.createLabel;
// SoundIconMorph stepping
/*
SoundIconMorph.prototype.step
= SpriteIconMorph.prototype.step;
*/
// SoundIconMorph layout
SoundIconMorph.prototype.fixLayout
= SpriteIconMorph.prototype.fixLayout;
// SoundIconMorph menu
SoundIconMorph.prototype.userMenu = function () {
var menu = new MenuMorph(this);
if (!(this.object instanceof Sound)) { return null; }
menu.addItem('rename', 'renameSound');
menu.addItem('delete', 'removeSound');
menu.addLine();
menu.addItem('export', 'exportSound');
return menu;
};
SoundIconMorph.prototype.renameSound = function () {
var sound = this.object,
ide = this.parentThatIsA(IDE_Morph),
myself = this;
this.disinherit();
(new DialogBoxMorph(
null,
function (answer) {
if (answer && (answer !== sound.name)) {
sound.name = answer;
sound.version = Date.now();
myself.createLabel(); // can be omitted once I'm stepping
myself.fixLayout(); // can be omitted once I'm stepping
ide.hasChangedMedia = true;
}
}
)).prompt(
'rename sound',
sound.name,
this.world()
);
};
SoundIconMorph.prototype.removeSound = function () {
var jukebox = this.parentThatIsA(JukeboxMorph),
idx = this.parent.children.indexOf(this) - 1;
jukebox.removeSound(idx);
};
SoundIconMorph.prototype.exportSound = function () {
var ide = this.parentThatIsA(IDE_Morph);
ide.saveAudioAs(this.object.audio, this.object.name);
};
SoundIconMorph.prototype.render
= SpriteIconMorph.prototype.render;
SoundIconMorph.prototype.createLabel
= SpriteIconMorph.prototype.createLabel;
// SoundIconMorph inheritance
SoundIconMorph.prototype.disinherit = function () {
var jukebox = this.parentThatIsA(JukeboxMorph),
idx = this.parent.children.indexOf(this);
if (jukebox.sprite.inheritsAttribute('sounds')) {
jukebox.sprite.shadowAttribute('sounds');
this.object = jukebox.sprite.sounds.at(idx - 1);
}
};
// SoundIconMorph drag & drop
SoundIconMorph.prototype.prepareToBeGrabbed = function () {
this.disinherit();
this.userState = 'pressed';
this.state = true;
this.rerender();
this.removeSound();
};
// JukeboxMorph /////////////////////////////////////////////////////
/*
I am JukeboxMorph, like WardrobeMorph, but for sounds
*/
// JukeboxMorph instance creation
JukeboxMorph.prototype = new ScrollFrameMorph();
JukeboxMorph.prototype.constructor = JukeboxMorph;
JukeboxMorph.uber = ScrollFrameMorph.prototype;
function JukeboxMorph(aSprite, sliderColor) {
this.init(aSprite, sliderColor);
}
JukeboxMorph.prototype.init = function (aSprite, sliderColor) {
// additional properties
this.sprite = aSprite || new SpriteMorph();
this.soundsVersion = null;
this.spriteVersion = null;
// initialize inherited properties
JukeboxMorph.uber.init.call(this, null, null, sliderColor);
// configure inherited properties
this.acceptsDrops = false;
this.fps = 2;
this.updateList();
};
// Jukebox updating
JukeboxMorph.prototype.updateList = function () {
var myself = this,
x = this.left() + 5,
y = this.top() + 5,
padding = 4,
icon,
txt,
ide = this.sprite.parentThatIsA(IDE_Morph),
recordButton;
this.changed();
this.contents.destroy();
this.contents = new FrameMorph(this);
this.contents.acceptsDrops = false;
this.contents.reactToDropOf = function (icon) {
myself.reactToDropOf(icon);
};
this.addBack(this.contents);
txt = new TextMorph(localize(
'import a sound from your computer\nby dragging it into here'
));
txt.fontSize = 9;
txt.setColor(SpriteMorph.prototype.paletteTextColor);
txt.setPosition(new Point(x, y));
this.addContents(txt);
recordButton = new PushButtonMorph(
ide,
'recordNewSound',
new SymbolMorph('circleSolid', 15)
);
recordButton.padding = 0;
recordButton.corner = 12;
recordButton.color = IDE_Morph.prototype.groupColor;
recordButton.highlightColor = IDE_Morph.prototype.frameColor.darker(50);
recordButton.pressColor = recordButton.highlightColor;
recordButton.labelMinExtent = new Point(36, 18);
recordButton.labelShadowOffset = new Point(-1, -1);
recordButton.labelShadowColor = recordButton.highlightColor;
recordButton.labelColor = TurtleIconMorph.prototype.labelColor;
recordButton.contrast = this.buttonContrast;
recordButton.hint = 'Record a new sound';
recordButton.fixLayout();
recordButton.label.setColor(new Color(255, 20, 20));
recordButton.setPosition(txt.bottomLeft().add(new Point(0, padding * 2)));
this.addContents(recordButton);
y = recordButton.bottom() + padding;
this.sprite.sounds.asArray().forEach(function (sound) {
icon = new SoundIconMorph(sound);
icon.setPosition(new Point(x, y));
myself.addContents(icon);
y = icon.bottom() + padding;
});
this.soundsVersion = this.sprite.sounds.lastChanged;
this.changed();
this.updateSelection();
};
JukeboxMorph.prototype.updateSelection = function () {
this.contents.children.forEach(function (morph) {
if (morph.refresh) {morph.refresh(); }
});
this.spriteVersion = this.sprite.version;
};
// Jukebox stepping
JukeboxMorph.prototype.step = function () {
if (this.soundsVersion !== this.sprite.sounds.lastChanged) {
this.updateList();
}
if (this.spriteVersion !== this.sprite.version) {
this.updateSelection();
}
};
// Jukebox ops
JukeboxMorph.prototype.removeSound = function (idx) {
this.sprite.sounds.remove(idx);
this.updateList();
};
// Jukebox drag & drop
JukeboxMorph.prototype.wantsDropOf = function (morph) {
return morph instanceof SoundIconMorph;
};
JukeboxMorph.prototype.reactToDropOf = function (icon) {
var idx = 0,
costume = icon.object,
top = icon.top();
icon.destroy();
this.contents.children.forEach(function (item) {
if (item instanceof SoundIconMorph && item.top() < top - 4) {
idx += 1;
}
});
this.sprite.shadowAttribute('sounds');
this.sprite.sounds.add(costume, idx + 1);
this.updateList();
};
// StageHandleMorph ////////////////////////////////////////////////////////
// I am a horizontal resizing handle for a StageMorph
// StageHandleMorph inherits from Morph:
StageHandleMorph.prototype = new Morph();
StageHandleMorph.prototype.constructor = StageHandleMorph;
StageHandleMorph.uber = Morph.prototype;
// StageHandleMorph instance creation:
function StageHandleMorph(target) {
this.init(target);
}
StageHandleMorph.prototype.init = function (target) {
this.target = target || null;
this.userState = 'normal'; // or 'highlight'
HandleMorph.uber.init.call(this);
this.color = MorphicPreferences.isFlat ?
IDE_Morph.prototype.backgroundColor : new Color(190, 190, 190);
this.isDraggable = false;
this.setExtent(new Point(12, 50));
};
// StageHandleMorph drawing:
StageHandleMorph.prototype.render = function (ctx) {
if (this.userState === 'highlight') {
this.renderOn(
ctx,
MorphicPreferences.isFlat ?
new Color(245, 245, 255) : new Color(100, 100, 255),
this.color
);
} else { // assume 'normal'
this.renderOn(ctx, this.color);
}
};
StageHandleMorph.prototype.renderOn = function (
ctx,
color,
shadowColor
) {
var l = this.height() / 8,
w = this.width() / 6,
r = w / 2,
x,
y,
i;
ctx.lineWidth = w;
ctx.lineCap = 'round';
y = this.height() / 2;
ctx.strokeStyle = color.toString();
x = this.width() / 12;
for (i = 0; i < 3; i += 1) {
if (i > 0) {
ctx.beginPath();
ctx.moveTo(x, y - (l - r));
ctx.lineTo(x, y + (l - r));
ctx.stroke();
}
x += (w * 2);
l *= 2;
}
if (shadowColor) {
ctx.strokeStyle = shadowColor.toString();
x = this.width() / 12 + w;
l = this.height() / 8;
for (i = 0; i < 3; i += 1) {
if (i > 0) {
ctx.beginPath();
ctx.moveTo(x, y - (l - r));
ctx.lineTo(x, y + (l - r));
ctx.stroke();
}
x += (w * 2);
l *= 2;
}
}
};
// StageHandleMorph layout:
StageHandleMorph.prototype.fixLayout = function () {
if (!this.target) {return; }
var ide = this.target.parentThatIsA(IDE_Morph);
this.setTop(this.target.top() + 10);
this.setRight(this.target.left());
if (ide) {ide.add(this); } // come to front
};
// StageHandleMorph stepping:
StageHandleMorph.prototype.step = null;
StageHandleMorph.prototype.mouseDownLeft = function (pos) {
var world = this.world(),
offset = this.right() - pos.x,
myself = this,
ide = this.target.parentThatIsA(IDE_Morph);
if (!this.target) {
return null;
}
ide.isSmallStage = true;
ide.controlBar.stageSizeButton.refresh();
this.step = function () {
var newPos, newWidth;
if (world.hand.mouseButton) {
newPos = world.hand.bounds.origin.x + offset;
newWidth = myself.target.right() - newPos;
ide.stageRatio = newWidth / myself.target.dimensions.x;
ide.setExtent(world.extent());
} else {
this.step = null;
ide.isSmallStage = (ide.stageRatio !== 1);
ide.controlBar.stageSizeButton.refresh();
}
};
};
// StageHandleMorph events:
StageHandleMorph.prototype.mouseEnter = function () {
this.userState = 'highlight';
this.rerender();
};
StageHandleMorph.prototype.mouseLeave = function () {
this.userState = 'normal';
this.rerender();
};
StageHandleMorph.prototype.mouseDoubleClick = function () {
this.target.parentThatIsA(IDE_Morph).toggleStageSize(true, 1);
};
// PaletteHandleMorph ////////////////////////////////////////////////////////
// I am a horizontal resizing handle for a blocks palette
// I pseudo-inherit many things from StageHandleMorph
// PaletteHandleMorph inherits from Morph:
PaletteHandleMorph.prototype = new Morph();
PaletteHandleMorph.prototype.constructor = PaletteHandleMorph;
PaletteHandleMorph.uber = Morph.prototype;
// PaletteHandleMorph instance creation:
function PaletteHandleMorph(target) {
this.init(target);
}
PaletteHandleMorph.prototype.init = function (target) {
this.target = target || null;
this.userState = 'normal';
HandleMorph.uber.init.call(this);
this.color = MorphicPreferences.isFlat ?
IDE_Morph.prototype.backgroundColor : new Color(190, 190, 190);
this.isDraggable = false;
this.setExtent(new Point(12, 50));
};
// PaletteHandleMorph drawing:
PaletteHandleMorph.prototype.render =
StageHandleMorph.prototype.render;
PaletteHandleMorph.prototype.renderOn =
StageHandleMorph.prototype.renderOn;
// PaletteHandleMorph layout:
PaletteHandleMorph.prototype.fixLayout = function () {
if (!this.target) {return; }
var ide = this.target.parentThatIsA(IDE_Morph);
this.setTop(this.target.top() + 10);
this.setRight(this.target.right());
if (ide) {ide.add(this); } // come to front
};
// PaletteHandleMorph stepping:
PaletteHandleMorph.prototype.step = null;
PaletteHandleMorph.prototype.mouseDownLeft = function (pos) {
var world = this.world(),
offset = this.right() - pos.x,
ide = this.target.parentThatIsA(IDE_Morph);
if (!this.target) {
return null;
}
this.step = function () {
var newPos;
if (world.hand.mouseButton) {
newPos = world.hand.bounds.origin.x + offset;
ide.paletteWidth = Math.min(
Math.max(200, newPos),
ide.stageHandle.left() - ide.spriteBar.tabBar.width()
);
ide.setExtent(world.extent());
} else {
this.step = null;
}
};
};
// PaletteHandleMorph events:
PaletteHandleMorph.prototype.mouseEnter
= StageHandleMorph.prototype.mouseEnter;
PaletteHandleMorph.prototype.mouseLeave
= StageHandleMorph.prototype.mouseLeave;
PaletteHandleMorph.prototype.mouseDoubleClick = function () {
this.target.parentThatIsA(IDE_Morph).setPaletteWidth(200);
};
// CamSnapshotDialogMorph ////////////////////////////////////////////////////
/*
I am a dialog morph that lets users take a snapshot using their webcam
and use it as a costume for their sprites or a background for the Stage.
NOTE: Currently disabled because of issues with experimental technology
in Safari.
*/
// CamSnapshotDialogMorph inherits from DialogBoxMorph:
CamSnapshotDialogMorph.prototype = new DialogBoxMorph();
CamSnapshotDialogMorph.prototype.constructor = CamSnapshotDialogMorph;
CamSnapshotDialogMorph.uber = DialogBoxMorph.prototype;
// CamSnapshotDialogMorph settings
CamSnapshotDialogMorph.prototype.enableCamera = true; // off while experimental
CamSnapshotDialogMorph.prototype.enabled = true;
CamSnapshotDialogMorph.prototype.notSupportedMessage =
'Please make sure your web browser is up to date\n' +
'and your camera is properly configured. \n\n' +
'Some browsers also require you to access Snap!\n' +
'through HTTPS to use the camera.\n\n' +
'Plase replace the "http://" part of the address\n' +
'in your browser by "https://" and try again.';
// CamSnapshotDialogMorph instance creation
function CamSnapshotDialogMorph(ide, sprite, onCancel, onAccept) {
this.init(ide, sprite, onCancel, onAccept);
}
CamSnapshotDialogMorph.prototype.init = function (
ide,
sprite,
onCancel,
onAccept
) {
this.ide = ide;
this.sprite = sprite;
this.padding = 10;
this.oncancel = onCancel;
this.accept = onAccept;
this.videoElement = null; // an HTML5 video element
this.videoView = new Morph(); // a morph where we'll copy the video contents
this.videoView.isCachingImage = true;
CamSnapshotDialogMorph.uber.init.call(this);
this.labelString = 'Camera';
this.createLabel();
this.buildContents();
};
CamSnapshotDialogMorph.prototype.buildContents = function () {
var myself = this,
stage = this.sprite.parentThatIsA(StageMorph);
function noCameraSupport() {
myself.disable();
myself.ide.inform(
'Camera not supported',
CamSnapshotDialogMorph.prototype.notSupportedMessage
);
if (myself.videoElement) {
myself.videoElement.remove();
}
myself.cancel();
}
this.videoElement = document.createElement('video');
this.videoElement.hidden = true;
this.videoElement.width = stage.dimensions.x;
this.videoElement.height = stage.dimensions.y;
document.body.appendChild(this.videoElement);
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
myself.videoElement.srcObject = stream;
myself.videoElement.play().catch(noCameraSupport);
myself.videoElement.stream = stream;
})
.catch(noCameraSupport);
}
this.videoView.setExtent(stage.dimensions);
this.videoView.cachedImage = newCanvas(
stage.dimensions,
true, // retina, maybe overkill here
this.videoView.cachedImage
);
this.videoView.drawOn = function (ctx, rect) {
var videoWidth = myself.videoElement.videoWidth,
videoHeight = myself.videoElement.videoHeight,
w = stage.dimensions.x,
h = stage.dimensions.y,
clippingWidth, clippingHeight;
if (!videoWidth) { return; }
ctx.save();
// Flip the image so it looks like a mirror
ctx.translate(w, 0);
ctx.scale(-1, 1);
if (videoWidth / w > videoHeight / h) {
// preserve height, crop width
clippingWidth = w * (videoHeight / h);
clippingHeight = videoHeight;
} else {
// preserve width, crop height
clippingWidth = videoWidth;
clippingHeight = h * (videoWidth / w);
}
ctx.drawImage(
myself.videoElement,
0,
0,
clippingWidth,
clippingHeight,
this.left() * -1,
this.top(),
w,
h
);
ctx.restore();
};
this.videoView.step = function () {
this.changed();
};
this.addBody(new AlignmentMorph('column', this.padding / 2));
this.body.add(this.videoView);
this.body.fixLayout();
this.addButton('ok', 'Save');
this.addButton('cancel', 'Cancel');
this.fixLayout();
this.rerender();
};
CamSnapshotDialogMorph.prototype.ok = function () {
this.accept(
new Costume(
this.videoView.fullImage(),
this.sprite.newCostumeName('camera')
).flipped()
);
};
CamSnapshotDialogMorph.prototype.disable = function () {
CamSnapshotDialogMorph.prototype.enabled = false;
document.dispatchEvent(new Event('cameraDisabled'));
};
CamSnapshotDialogMorph.prototype.destroy = function () {
this.oncancel.call(this);
this.close();
};
CamSnapshotDialogMorph.prototype.close = function () {
if (this.videoElement && this.videoElement.stream) {
this.videoElement.stream.getTracks()[0].stop();
this.videoElement.remove();
}
CamSnapshotDialogMorph.uber.destroy.call(this);
};
// SoundRecorderDialogMorph ////////////////////////////////////////////////////
/*
I am a dialog morph that lets users record sound snippets for their
sprites or Stage.
*/
// SoundRecorderDialogMorph inherits from DialogBoxMorph:
SoundRecorderDialogMorph.prototype = new DialogBoxMorph();
SoundRecorderDialogMorph.prototype.constructor = SoundRecorderDialogMorph;
SoundRecorderDialogMorph.uber = DialogBoxMorph.prototype;
// SoundRecorderDialogMorph instance creation
function SoundRecorderDialogMorph(onAccept) {
this.init(onAccept);
}
SoundRecorderDialogMorph.prototype.init = function (onAccept) {
var myself = this;
this.padding = 10;
this.accept = onAccept;
this.mediaRecorder = null; // an HTML5 MediaRecorder object
this.audioElement = document.createElement('audio');
this.audioElement.hidden = true;
this.audioElement.onended = function (event) {
myself.stop();
};
document.body.appendChild(this.audioElement);
this.recordButton = null;
this.stopButton = null;
this.playButton = null;
this.progressBar = new BoxMorph();
SoundRecorderDialogMorph.uber.init.call(this);
this.labelString = 'Sound Recorder';
this.createLabel();
this.buildContents();
};
SoundRecorderDialogMorph.prototype.buildContents = function () {
var myself = this,
audioChunks = [];
this.recordButton = new PushButtonMorph(
this,
'record',
new SymbolMorph('circleSolid', 10)
);
this.stopButton = new PushButtonMorph(
this,
'stop',
new SymbolMorph('rectangleSolid', 10)
);
this.playButton = new PushButtonMorph(
this,
'play',
new SymbolMorph('pointRight', 10)
);
this.buildProgressBar();
this.addBody(new AlignmentMorph('row', this.padding));
this.body.add(this.recordButton);
this.body.add(this.stopButton);
this.body.add(this.playButton);
this.body.add(this.progressBar);
this.body.fixLayout();
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(
{
audio: {
channelCount: 1 // force mono, currently only works on FF
}
}
).then(function (stream) {
myself.mediaRecorder = new MediaRecorder(stream);
myself.mediaRecorder.ondataavailable = function (event) {
audioChunks.push(event.data);
};
myself.mediaRecorder.onstop = function (event) {
var buffer = new Blob(audioChunks),
reader = new window.FileReader();
reader.readAsDataURL(buffer);
reader.onloadend = function() {
var base64 = reader.result;
base64 = 'data:audio/ogg;base64,' +
base64.split(',')[1];
myself.audioElement.src = base64;
myself.audioElement.load();
audioChunks = [];
};
};
});
}
this.addButton('ok', 'Save');
this.addButton('cancel', 'Cancel');
this.fixLayout();
this.rerender();
};
SoundRecorderDialogMorph.prototype.buildProgressBar = function () {
var line = new Morph(),
myself = this;
this.progressBar.setExtent(new Point(150, 20));
this.progressBar.setColor(new Color(200, 200, 200));
this.progressBar.setBorderWidth(1);
this.progressBar.setBorderColor(new Color(150, 150, 150));
line.setExtent(new Point(130, 2));
line.setColor(new Color(50, 50, 50));
line.setCenter(this.progressBar.center());
this.progressBar.add(line);
this.progressBar.indicator = new Morph();
this.progressBar.indicator.setExtent(new Point(5, 15));
this.progressBar.indicator.setColor(new Color(50, 200, 50));
this.progressBar.indicator.setCenter(line.leftCenter());
this.progressBar.add(this.progressBar.indicator);
this.progressBar.setPercentage = function (percentage) {
this.indicator.setLeft(
line.left() +
(line.width() / 100 * percentage) -
this.indicator.width() / 2
);
};
this.progressBar.step = function () {
if (myself.audioElement.duration) {
this.setPercentage(
myself.audioElement.currentTime /
myself.audioElement.duration * 100);
} else {
this.setPercentage(0);
}
};
};
SoundRecorderDialogMorph.prototype.record = function () {
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
this.stop();
return;
}
this.mediaRecorder.start();
this.recordButton.label.setColor(new Color(255, 0, 0));
this.playButton.label.setColor(new Color(0, 0, 0));
};
SoundRecorderDialogMorph.prototype.stop = function () {
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
this.mediaRecorder.stop();
}
this.audioElement.pause();
this.audioElement.currentTime = 0;
this.recordButton.label.setColor(new Color(0, 0, 0));
this.playButton.label.setColor(new Color(0, 0, 0));
};
SoundRecorderDialogMorph.prototype.play = function () {
this.stop();
this.audioElement.oncanplaythrough = function () {
this.play();
this.oncanplaythrough = nop;
};
this.playButton.label.setColor(new Color(0, 255, 0));
};
SoundRecorderDialogMorph.prototype.ok = function () {
var myself = this;
this.stop();
this.audioElement.oncanplaythrough = function () {
if (this.duration && this.duration !== Infinity) {
myself.accept(this);
this.oncanplaythrough = nop;
myself.destroy();
} else {
// For some reason, we need to play the sound
// at least once to get its duration.
myself.buttons.children.forEach(function (button) {
button.disable();
});
this.play();
}
};
};
SoundRecorderDialogMorph.prototype.destroy = function () {
this.stop();
this.audioElement.remove();
if (this.mediaRecorder) {
this.mediaRecorder.stream.getTracks()[0].stop();
}
SoundRecorderDialogMorph.uber.destroy.call(this);
};
| refactored more cloud ops in the IDE
| src/gui.js | refactored more cloud ops in the IDE | <ide><path>rc/gui.js
<ide> };
<ide>
<ide> IDE_Morph.prototype.cloudAcknowledge = function () {
<del> var myself = this;
<del> return function (responseText, url) {
<add> return (responseText, url) => {
<ide> nop(responseText);
<ide> new DialogBoxMorph().inform(
<ide> 'Cloud Connection',
<ide> 'Successfully connected to:\n'
<ide> + 'http://'
<ide> + url,
<del> myself.world(),
<del> myself.cloudIcon(null, new Color(0, 180, 0))
<add> this.world(),
<add> this.cloudIcon(null, new Color(0, 180, 0))
<ide> );
<ide> };
<ide> };
<ide>
<ide> IDE_Morph.prototype.cloudResponse = function () {
<del> var myself = this;
<del> return function (responseText, url) {
<add> return (responseText, url) => {
<ide> var response = responseText;
<ide> if (response.length > 50) {
<ide> response = response.substring(0, 50) + '...';
<ide> + url + ':\n\n'
<ide> + 'responds:\n'
<ide> + response,
<del> myself.world(),
<del> myself.cloudIcon(null, new Color(0, 180, 0))
<add> this.world(),
<add> this.cloudIcon(null, new Color(0, 180, 0))
<ide> );
<ide> };
<ide> };
<ide>
<ide> IDE_Morph.prototype.cloudError = function () {
<del> var myself = this;
<del>
<del> // try finding an eplanation what's going on
<del> // has some issues, commented out for now
<del> /*
<del> function getURL(url) {
<del> try {
<del> var request = new XMLHttpRequest();
<del> request.open('GET', url, false);
<del> request.send();
<del> if (request.status === 200) {
<del> return request.responseText;
<del> }
<del> return null;
<del> } catch (err) {
<del> return null;
<del> }
<del> }
<del> */
<del>
<del> return function (responseText, url) {
<add> return (responseText, url) => {
<ide> // first, try to find out an explanation for the error
<ide> // and notify the user about it,
<ide> // if none is found, show an error dialog box
<ide> var response = responseText,
<ide> // explanation = getURL('https://snap.berkeley.edu/cloudmsg.txt'),
<ide> explanation = null;
<del> if (myself.shield) {
<del> myself.shield.destroy();
<del> myself.shield = null;
<add> if (this.shield) {
<add> this.shield.destroy();
<add> this.shield = null;
<ide> }
<ide> if (explanation) {
<del> myself.showMessage(explanation);
<add> this.showMessage(explanation);
<ide> return;
<ide> }
<ide> new DialogBoxMorph().inform(
<ide> 'Snap!Cloud',
<ide> (url ? url + '\n' : '')
<ide> + response,
<del> myself.world(),
<del> myself.cloudIcon(null, new Color(180, 0, 0))
<add> this.world(),
<add> this.cloudIcon(null, new Color(180, 0, 0))
<ide> );
<ide> };
<ide> };
<ide> };
<ide>
<ide> IDE_Morph.prototype.setCloudURL = function () {
<del> var myself = this;
<ide> new DialogBoxMorph(
<ide> null,
<del> function (url) {
<del> myself.cloud.url = url;
<del> }
<add> url => this.cloud.url = url
<ide> ).withKey('cloudURL').prompt(
<ide> 'Cloud URL',
<ide> this.cloud.url,
<ide>
<ide> IDE_Morph.prototype.urlParameters = function () {
<ide> var parameters = location.hash.slice(location.hash.indexOf(':') + 1);
<del>
<ide> return this.cloud.parseDict(parameters);
<ide> };
<ide>
<ide> IDE_Morph.prototype.hasCloudProject = function () {
<ide> var params = this.urlParameters();
<del>
<ide> return params.hasOwnProperty('Username') &&
<ide> params.hasOwnProperty('ProjectName');
<ide> }; |
|
JavaScript | apache-2.0 | fffed1d8dd6148897da83adb783ac3f9582c37e8 | 0 | nimishzynga/ns_server,nimishzynga/ns_server,mschoch/ns_server,membase/ns_server,membase/ns_server,membase/ns_server,membase/ns_server,nimishzynga/ns_server,t3rm1n4l/ns_server,membase/ns_server,ceejatec/ns_server,mschoch/ns_server,t3rm1n4l/ns_server,ceejatec/ns_server,nimishzynga/ns_server,ceejatec/ns_server,membase/ns_server,t3rm1n4l/ns_server,ceejatec/ns_server,t3rm1n4l/ns_server,t3rm1n4l/ns_server,mschoch/ns_server,ceejatec/ns_server,nimishzynga/ns_server,mschoch/ns_server,mschoch/ns_server,ceejatec/ns_server,nimishzynga/ns_server,mschoch/ns_server | /**
Copyright 2011 Couchbase, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
function createLogsSectionCells (ns, modeCell, stalenessCell, tasksProgressCell, logsSectionTabs, serversCell, isROAdminCell) {
ns.activeTabCell = Cell.needing(modeCell).compute(function (v, mode) {
return (mode === "log") || undefined;
}).name('activeTabCell');
ns.logsRawCell = Cell.needing(ns.activeTabCell).compute(function (v, active) {
return future.get({url: "/logs"});
}).name('logsRawCell');
ns.logsRawCell.keepValueDuringAsync = true;
ns.massagedLogsCell = Cell.compute(function (v) {
var logsValue = v(ns.logsRawCell);
var stale = v.need(stalenessCell);
if (logsValue === undefined) {
if (!stale){
return;
}
logsValue = {list: []};
}
return _.extend({}, logsValue, {stale: stale});
}).name('massagedLogsCell');
ns.isCollectionInfoTabCell = Cell.compute(function (v) {
return v.need(logsSectionTabs) === "collection_info" &&
v.need(ns.activeTabCell) && !v.need(isROAdminCell);
}).name("isClusterTabCell");
ns.isCollectionInfoTabCell.equality = _.isEqual;
ns.tasksCollectionInfoCell = Cell.computeEager(function (v) {
if (!v.need(ns.isCollectionInfoTabCell)) {
return null;
}
var tasks = v.need(tasksProgressCell);
var task = _.detect(tasks, function (taskInfo) {
return taskInfo.type === "clusterLogsCollection";
});
if (!task) {
return {
nodesByStatus: {},
nodeErrors: [],
status: 'idle',
perNode: {}
}
}
// this is cheap deep cloning of task. We're going to add some
// attributes there and it's best to avoid mutating part of
// tasksProgressCell value
task = JSON.parse(JSON.stringify(task));
var perNodeHash = task.perNode;
var perNode = [];
var cancallable = "starting started startingUpload startedUpload".split(" ");
var nodes = v.need(serversCell).allNodes;
_.each(perNodeHash, function (ni, nodeName) {
var node = _.detect(nodes, function (n) {
return n.otpNode === nodeName;
});
ni.nodeName = (node === undefined) ? nodeName.replace(/^.*?@/, '') :
ViewHelpers.stripPortHTML(node.hostname, nodes);
perNode.push(ni);
// possible per-node statuses are:
// starting, started, failed, collected,
// startingUpload, startedUpload, failedUpload, uploaded
if (task.status == 'cancelled' && cancallable.indexOf(ni.status) >= 0) {
ni.status = 'cancelled';
}
});
var nodesByStatus = _.groupBy(perNode, 'status');
var nodeErrors = _.compact(_.map(perNode, function (ni) {
if (ni.uploadOutput) {
return {nodeName: ni.nodeName,
error: ni.uploadOutput};
}
}));
task.nodesByStatus = nodesByStatus;
task.nodeErrors = nodeErrors;
return task;
}).name("tasksCollectionInfoCell");
ns.tasksCollectionInfoCell.equality = _.isEqual;
ns.prepareCollectionInfoNodesCell = Cell.computeEager(function (v) {
if (!v.need(ns.isCollectionInfoTabCell)) {
return null;
}
var nodes = v.need(serversCell).allNodes;
return {
nodes: _(nodes).map(function (node) {
return {
nodeClass: node.nodeClass,
value: node.otpNode,
isUnhealthy: node.status === 'unhealthy',
hostname: ViewHelpers.stripPortHTML(node.hostname, nodes)
};
})
}
}).name("prepareCollectionInfoNodesCell");
ns.prepareCollectionInfoNodesCell.equality = _.isEqual;
}
var LogsSection = {
init: function () {
var collectInfoStartNewView = $("#js_collect_info_start_new_view");
var selectNodesListCont = $("#js_select_nodes_list_container");
var uploadToCouchbase = $("#js_upload_to_cb");
var uploadToHost = $("#js_uploadHost_input");
var uploadToForm = $("#js_upload_conf");
var collectForm = $("#js_collect_info_form");
var collectFromRadios = $("input[name='from']", collectInfoStartNewView);
var cancelCollectBtn = $("#js_cancel_collect_info");
var startNewCollectBtn = $("#js_start_new_info");
var collectInfoWrapper = $("#js_collect_information");
var collectResultView = $("#js_collect_result_view");
var collectResultSectionSpinner = $("#js_collect_info_spinner");
var showResultViewBtn = $("#js_previous_result_btn");
var cancelConfiramationDialog = $("#js_cancel_collection_confirmation_dialog");
var saveButton = $(".js_save_button", collectInfoWrapper);
var collectInfoViewNameCell = new StringHashFragmentCell("collectInfoViewName");
var allActiveNodeBoxes;
var allNodeBoxes;
var overlayCollectInfoStartNewView;
var self = this;
collectResultSectionSpinner.show();
collectResultView.hide();
collectInfoStartNewView.hide();
self.tabs = new TabsCell('logsTabs', '#js_logs .tabs', '#js_logs .panes > div', ['logs', 'collection_info']);
createLogsSectionCells(
self,
DAL.cells.mode,
IOCenter.staleness,
DAL.cells.tasksProgressCell,
LogsSection.tabs,
DAL.cells.serversCell,
DAL.cells.isROAdminCell
);
renderCellTemplate(self.massagedLogsCell, 'logs', {
valueTransformer: function (value) {
var list = value.list || [];
return _.clone(list).reverse();
}
});
cancelCollectBtn.click(function (e) {
if (cancelCollectBtn.hasClass('dynamic_disabled')) {
return;
}
e.preventDefault();
showDialog(cancelConfiramationDialog, {
eventBindings: [['.save_button', 'click', function (e) {
e.preventDefault();
hideDialog(cancelConfiramationDialog);
$.ajax({
url: '/controller/cancelLogsCollection',
type: "POST",
success: function () {
recalculateTasksUri();
cancelCollectBtn.addClass('dynamic_disabled');
},
error: recalculateTasksUri
});
}]]
});
});
startNewCollectBtn.click(function (e) {
e.preventDefault();
collectInfoViewNameCell.setValue("startNew");
});
showResultViewBtn.click(function (e) {
e.preventDefault();
collectInfoViewNameCell.setValue("result");
});
collectForm.submit(function (e) {
e.preventDefault();
hideErrors();
var formValues = getCollectFormValues();
if (formValues["upload"]) {
if (!formValues["customer"]) {
showCollectInfoErrors("customer field must be given if upload is selected", "customer");
}
if (!formValues["uploadHost"]) {
showCollectInfoErrors("upload host field must be given if upload is selected", "uploadHost");
}
if (!formValues["uploadHost"] || !formValues["customer"]) {
return;
}
}
saveButton.attr('disabled', true);
delete formValues["upload"];
var overlayCollectForm = overlayWithSpinner(collectForm);
jsonPostWithErrors('/controller/startLogsCollection', $.param(formValues), function (commonError, status, perFieldErrors) {
overlayCollectForm.remove();
saveButton.attr('disabled', false);
if (status === 'success') {
overlayCollectInfoStartNewView = overlayWithSpinner(collectInfoStartNewView);
showResultViewBtn.hide();
self.tasksCollectionInfoCell.changedSlot.subscribeOnce(function () {
collectInfoViewNameCell.setValue("result");
});
recalculateTasksUri();
} else {
handleCollectInfoServersError(commonError, perFieldErrors);
}
});
});
uploadToCouchbase.change(function (e) {
$('input[type="text"]', uploadToForm).attr('disabled', !$(this).attr('checked'));
});
collectFromRadios.change(function (e) {
if (!allActiveNodeBoxes) {
return;
}
var isAllnodesChecked = $(this).val() == '*';
if (isAllnodesChecked) {
allNodeBoxes.attr({checked: true, disabled: true});
} else {
allNodeBoxes.attr({checked: false});
allActiveNodeBoxes.attr({checked: true, disabled: false});
}
maybeDisableSaveBtn();
});
function getCollectFormValues() {
var dataArray = collectForm.serializeArray();
var params = {'selected-nodes': []};
_.each(dataArray, function (pair) {
var name = pair.name;
var value = pair.value;
if (name === 'js-selected-nodes') {
params['selected-nodes'].push(value);
} else {
params[name] = value;
}
});
if (params['from'] === '*') {
delete params['from'];
delete params['selected-nodes'];
params['nodes'] = '*';
} else {
delete params['from'];
params['nodes'] = params['selected-nodes'].join(',');
delete params['selected-nodes'];
}
_.each(["uploadHost", "customer", "ticket"], function (k) {
if (params[k] === '') {
delete params[k];
}
});
return params;
}
function handleCollectInfoServersError(commonError, perFieldErrors) {
_.each((!!commonError.length ? commonError : perFieldErrors), showCollectInfoErrors);
}
function showCollectInfoErrors(value, key) {
key = key || 'generalCollectInfo';
$("#js_" + key + "_error").text(value).show();
$("#js_" + key + "_input").addClass("dynamic_input_error");
}
function hideErrors() {
$(".js_error_container", collectInfoStartNewView).hide();
$(".dynamic_input_error", collectInfoStartNewView).removeClass("dynamic_input_error");
}
function recalculateTasksUri() {
DAL.cells.tasksProgressURI.recalculate();
}
function hideResultButtons() {
startNewCollectBtn.hide();
cancelCollectBtn.hide();
}
function switchCollectionInfoView(isResultView, isCurrentlyRunning, isRunBefore) {
if (isResultView) {
collectInfoStartNewView.hide();
collectResultView.show();
showResultViewBtn.hide();
cancelCollectBtn.toggle(isCurrentlyRunning);
startNewCollectBtn.toggle(!isCurrentlyRunning);
collectForm[0].reset();
} else {
collectInfoStartNewView.show();
collectResultView.hide();
hideResultButtons();
hideErrors();
showResultViewBtn.toggle(isRunBefore);
}
}
function renderResultView(collectionInfo) {
renderTemplate('js_collect_progress', collectionInfo);
}
function maybeDisableSaveBtn() {
saveButton.attr('disabled', !jQuery('input:checked', selectNodesListCont).length);
}
function renderStartNewView() {
self.prepareCollectionInfoNodesCell.getValue(function (selectNodesList) {
renderTemplate('js_select_nodes_list', selectNodesList);
allActiveNodeBoxes = $('input:not(:disabled)', selectNodesListCont);
allNodeBoxes = $('input', selectNodesListCont);
allActiveNodeBoxes.change(maybeDisableSaveBtn);
collectFromRadios.eq(0).attr('checked', true).trigger('change');
uploadToCouchbase.attr('checked', false).trigger('change');
maybeDisableSaveBtn();
});
}
self.isCollectionInfoTabCell.subscribeValue(function (isCollectionInfoTab) {
if (!isCollectionInfoTab) {
hideResultButtons();
showResultViewBtn.hide();
}
});
DAL.cells.isEnterpriseCell.subscribeValue(function (isEnterprise) {
if (isEnterprise) {
uploadToHost.val('s3.amazonaws.com/cb-customers');
}
});
Cell.subscribeMultipleValues(function (collectionInfo, tabName) {
if (!collectionInfo) {
return;
}
var isCurrentlyRunning = collectionInfo.status === 'running';
var isRunBefore = !!_.keys(collectionInfo.perNode).length;
var isResultView = tabName === 'result';
!isCurrentlyRunning && cancelCollectBtn.removeClass('dynamic_disabled');
if (isCurrentlyRunning) {
collectInfoViewNameCell.setValue("result");
} else {
if (tabName) {
if (!isRunBefore) {
collectInfoViewNameCell.setValue("startNew");
}
} else {
var defaultTabName = isRunBefore ? "result": "startNew";
collectInfoViewNameCell.setValue(defaultTabName);
}
}
switchCollectionInfoView(isResultView, isCurrentlyRunning, isRunBefore);
collectResultSectionSpinner.hide();
if (overlayCollectInfoStartNewView) {
overlayCollectInfoStartNewView.remove();
}
if (isResultView) {
renderResultView(collectionInfo);
} else {
renderStartNewView();
}
}, self.tasksCollectionInfoCell, collectInfoViewNameCell);
self.massagedLogsCell.subscribeValue(function (massagedLogs) {
if (massagedLogs === undefined){
return;
}
var stale = massagedLogs.stale;
$('#js_logs .staleness-notice')[stale ? 'show' : 'hide']();
});
self.logsRawCell.subscribe(function (cell) {
cell.recalculateAfterDelay(30000);
});
},
onEnter: function () {
},
navClick: function () {
if (DAL.cells.mode.value == 'log'){
this.logsRawCell.recalculate();
}
},
domId: function (sec) {
return 'logs';
}
}
| priv/public/js/logs.js | /**
Copyright 2011 Couchbase, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
function createLogsSectionCells (ns, modeCell, stalenessCell, tasksProgressCell, logsSectionTabs, serversCell, isROAdminCell) {
ns.activeTabCell = Cell.needing(modeCell).compute(function (v, mode) {
return (mode === "log") || undefined;
}).name('activeTabCell');
ns.logsRawCell = Cell.needing(ns.activeTabCell).compute(function (v, active) {
return future.get({url: "/logs"});
}).name('logsRawCell');
ns.logsRawCell.keepValueDuringAsync = true;
ns.massagedLogsCell = Cell.compute(function (v) {
var logsValue = v(ns.logsRawCell);
var stale = v.need(stalenessCell);
if (logsValue === undefined) {
if (!stale){
return;
}
logsValue = {list: []};
}
return _.extend({}, logsValue, {stale: stale});
}).name('massagedLogsCell');
ns.isCollectionInfoTabCell = Cell.compute(function (v) {
return v.need(logsSectionTabs) === "collection_info" &&
v.need(ns.activeTabCell) && !v.need(isROAdminCell);
}).name("isClusterTabCell");
ns.isCollectionInfoTabCell.equality = _.isEqual;
ns.tasksCollectionInfoCell = Cell.computeEager(function (v) {
if (!v.need(ns.isCollectionInfoTabCell)) {
return null;
}
var tasks = v.need(tasksProgressCell);
var task = _.detect(tasks, function (taskInfo) {
return taskInfo.type === "clusterLogsCollection";
});
if (!task) {
return {
nodesByStatus: {},
nodeErrors: [],
status: 'idle',
perNode: {}
}
}
// this is cheap deep cloning of task. We're going to add some
// attributes there and it's best to avoid mutating part of
// tasksProgressCell value
task = JSON.parse(JSON.stringify(task));
var perNodeHash = task.perNode;
var perNode = [];
var cancallable = "starting started startingUpload startedUpload".split(" ");
var nodes = v.need(serversCell).allNodes;
_.each(perNodeHash, function (ni, nodeName) {
var node = _.detect(nodes, function (n) {
return n.otpNode === nodeName;
});
ni.nodeName = (node === undefined) ? nodeName.replace(/^.*?@/, '') :
ViewHelpers.stripPortHTML(node.hostname, nodes);
perNode.push(ni);
// possible per-node statuses are:
// starting, started, failed, collected,
// startingUpload, startedUpload, failedUpload, uploaded
if (task.status == 'cancelled' && cancallable.indexOf(ni.status) >= 0) {
ni.status = 'cancelled';
}
});
var nodesByStatus = _.groupBy(perNode, 'status');
var nodeErrors = _.compact(_.map(perNode, function (ni) {
if (ni.uploadOutput) {
return {nodeName: ni.nodeName,
error: ni.uploadOutput};
}
}));
task.nodesByStatus = nodesByStatus;
task.nodeErrors = nodeErrors;
return task;
}).name("tasksCollectionInfoCell");
ns.tasksCollectionInfoCell.equality = _.isEqual;
ns.prepareCollectionInfoNodesCell = Cell.computeEager(function (v) {
if (!v.need(ns.isCollectionInfoTabCell)) {
return null;
}
var nodes = v.need(serversCell).allNodes;
return {
nodes: _(nodes).map(function (node) {
return {
nodeClass: node.nodeClass,
value: node.otpNode,
isUnhealthy: node.status === 'unhealthy',
hostname: ViewHelpers.stripPortHTML(node.hostname, nodes)
};
})
}
}).name("prepareCollectionInfoNodesCell");
ns.prepareCollectionInfoNodesCell.equality = _.isEqual;
}
var LogsSection = {
init: function () {
var collectInfoStartNewView = $("#js_collect_info_start_new_view");
var selectNodesListCont = $("#js_select_nodes_list_container");
var uploadToCouchbase = $("#js_upload_to_cb");
var uploadToHost = $("#js_uploadHost_input");
var uploadToForm = $("#js_upload_conf");
var collectForm = $("#js_collect_info_form");
var collectFromRadios = $("input[name='from']", collectInfoStartNewView);
var cancelCollectBtn = $("#js_cancel_collect_info");
var startNewCollectBtn = $("#js_start_new_info");
var collectInfoWrapper = $("#js_collect_information");
var collectResultView = $("#js_collect_result_view");
var collectResultSectionSpinner = $("#js_collect_info_spinner");
var showResultViewBtn = $("#js_previous_result_btn");
var cancelConfiramationDialog = $("#js_cancel_collection_confirmation_dialog");
var saveButton = $(".js_save_button", collectInfoWrapper);
var collectInfoViewNameCell = new StringHashFragmentCell("collectInfoViewName");
var allActiveNodeBoxes;
var allNodeBoxes;
var overlay;
var self = this;
collectResultSectionSpinner.show();
collectResultView.hide();
collectInfoStartNewView.hide();
self.tabs = new TabsCell('logsTabs', '#js_logs .tabs', '#js_logs .panes > div', ['logs', 'collection_info']);
createLogsSectionCells(
self,
DAL.cells.mode,
IOCenter.staleness,
DAL.cells.tasksProgressCell,
LogsSection.tabs,
DAL.cells.serversCell,
DAL.cells.isROAdminCell
);
renderCellTemplate(self.massagedLogsCell, 'logs', {
valueTransformer: function (value) {
var list = value.list || [];
return _.clone(list).reverse();
}
});
cancelCollectBtn.click(function (e) {
if (cancelCollectBtn.hasClass('dynamic_disabled')) {
return;
}
e.preventDefault();
showDialog(cancelConfiramationDialog, {
eventBindings: [['.save_button', 'click', function (e) {
e.preventDefault();
hideDialog(cancelConfiramationDialog);
$.ajax({
url: '/controller/cancelLogsCollection',
type: "POST",
success: function () {
recalculateTasksUri();
cancelCollectBtn.addClass('dynamic_disabled');
},
error: recalculateTasksUri
});
}]]
});
});
startNewCollectBtn.click(function (e) {
e.preventDefault();
collectInfoViewNameCell.setValue("startNew");
});
showResultViewBtn.click(function (e) {
e.preventDefault();
collectInfoViewNameCell.setValue("result");
});
collectForm.submit(function (e) {
e.preventDefault();
var formValues = getCollectFormValues();
if (formValues["upload"]) {
var nonEmptyUpload = _.detect(("uploadHost customer ticket").split(" "), function (k) {
return formValues[k] !== undefined;
});
if (!nonEmptyUpload) {
var resp = JSON.stringify({"uploadHost": "upload host must be given if upload is selected",
"customer": "customer must be given if upload is selected"});
onError({responseText: resp});
return;
}
}
saveButton.attr('disabled', true);
delete formValues["upload"];
var overlayCollectForm = overlayWithSpinner(collectForm);
$.ajax({
type: 'POST',
url: '/controller/startLogsCollection',
data: formValues,
success: onSuccess,
error: onError,
complete: function () {
overlayCollectForm.remove();
saveButton.attr('disabled', false);
}
});
function onSuccess() {
overlay = overlayWithSpinner(collectInfoStartNewView);
showResultViewBtn.hide();
self.tasksCollectionInfoCell.changedSlot.subscribeOnce(function () {
collectInfoViewNameCell.setValue("result");
});
recalculateTasksUri();
hideErrors();
}
function onError(resp) {
hideErrors();
var errors = {};
try {
errors = JSON.parse(resp.responseText);
} catch (e) {
// nothing
console.log("failed to parse json errors: ", e);
}
console.log("Got errors: ", errors);
_.each(errors, function (value, key) {
if (key != '_') {
showErrors(key, value);
} else {
showErrors('generalCollectInfo', value);
}
});
}
});
uploadToCouchbase.change(function (e) {
$('input[type="text"]', uploadToForm).attr('disabled', !$(this).attr('checked'));
});
collectFromRadios.change(function (e) {
if (!allActiveNodeBoxes) {
return;
}
var isAllnodesChecked = $(this).val() == '*';
if (isAllnodesChecked) {
allNodeBoxes.attr({checked: true, disabled: true});
} else {
allNodeBoxes.attr({checked: false});
allActiveNodeBoxes.attr({checked: true, disabled: false});
}
maybeDisableSaveBtn();
});
function getCollectFormValues() {
var dataArray = collectForm.serializeArray();
var params = {'selected-nodes': []};
_.each(dataArray, function (pair) {
var name = pair.name;
var value = pair.value;
if (name === 'js-selected-nodes') {
params['selected-nodes'].push(value);
} else {
params[name] = value;
}
});
if (params['from'] === '*') {
delete params['from'];
delete params['selected-nodes'];
params['nodes'] = '*';
} else {
delete params['from'];
params['nodes'] = params['selected-nodes'].join(',');
delete params['selected-nodes'];
}
_.each(["uploadHost", "customer", "ticket"], function (k) {
if (params[k] === '') {
delete params[k];
}
});
return params;
}
function showErrors(key, value) {
$("#js_" + key + "_error").text(value).show();
$("#js_" + key + "_input").addClass("dynamic_input_error");
}
function hideErrors() {
$(".js_error_container", collectInfoStartNewView).hide();
$(".dynamic_input_error", collectInfoStartNewView).removeClass("dynamic_input_error");
}
function recalculateTasksUri() {
DAL.cells.tasksProgressURI.recalculate();
}
function hideResultButtons() {
startNewCollectBtn.hide();
cancelCollectBtn.hide();
}
function switchCollectionInfoView(isResultView, isCurrentlyRunning, isRunBefore) {
if (isResultView) {
collectInfoStartNewView.hide();
collectResultView.show();
showResultViewBtn.hide();
cancelCollectBtn.toggle(isCurrentlyRunning);
startNewCollectBtn.toggle(!isCurrentlyRunning);
collectForm[0].reset();
} else {
collectInfoStartNewView.show();
collectResultView.hide();
hideResultButtons();
hideErrors();
showResultViewBtn.toggle(isRunBefore);
}
}
function renderResultView(collectionInfo) {
renderTemplate('js_collect_progress', collectionInfo);
}
function maybeDisableSaveBtn() {
saveButton.attr('disabled', !jQuery('input:checked', selectNodesListCont).length);
}
function renderStartNewView() {
self.prepareCollectionInfoNodesCell.getValue(function (selectNodesList) {
renderTemplate('js_select_nodes_list', selectNodesList);
allActiveNodeBoxes = $('input:not(:disabled)', selectNodesListCont);
allNodeBoxes = $('input', selectNodesListCont);
allActiveNodeBoxes.change(maybeDisableSaveBtn);
collectFromRadios.eq(0).attr('checked', true).trigger('change');
uploadToCouchbase.attr('checked', false).trigger('change');
maybeDisableSaveBtn();
});
}
self.isCollectionInfoTabCell.subscribeValue(function (isCollectionInfoTab) {
if (!isCollectionInfoTab) {
hideResultButtons();
showResultViewBtn.hide();
}
});
DAL.cells.isEnterpriseCell.subscribeValue(function (isEnterprise) {
if (isEnterprise) {
uploadToHost.val('s3.amazonaws.com/cb-customers');
}
});
Cell.subscribeMultipleValues(function (collectionInfo, tabName) {
if (!collectionInfo) {
return;
}
var isCurrentlyRunning = collectionInfo.status === 'running';
var isRunBefore = !!_.keys(collectionInfo.perNode).length;
var isResultView = tabName === 'result';
!isCurrentlyRunning && cancelCollectBtn.removeClass('dynamic_disabled');
if (isCurrentlyRunning) {
collectInfoViewNameCell.setValue("result");
} else {
if (tabName) {
if (!isRunBefore) {
collectInfoViewNameCell.setValue("startNew");
}
} else {
var defaultTabName = isRunBefore ? "result": "startNew";
collectInfoViewNameCell.setValue(defaultTabName);
}
}
switchCollectionInfoView(isResultView, isCurrentlyRunning, isRunBefore);
collectResultSectionSpinner.hide();
if (overlay) {
overlay.remove();
}
if (isResultView) {
renderResultView(collectionInfo);
} else {
renderStartNewView();
}
}, self.tasksCollectionInfoCell, collectInfoViewNameCell);
self.massagedLogsCell.subscribeValue(function (massagedLogs) {
if (massagedLogs === undefined){
return;
}
var stale = massagedLogs.stale;
$('#js_logs .staleness-notice')[stale ? 'show' : 'hide']();
});
self.logsRawCell.subscribe(function (cell) {
cell.recalculateAfterDelay(30000);
});
},
onEnter: function () {
},
navClick: function () {
if (DAL.cells.mode.value == 'log'){
this.logsRawCell.recalculate();
}
},
domId: function (sec) {
return 'logs';
}
}
| MB-11697: improved collect infos error handler
[[email protected]: fixed typo]
[[email protected]: added ticket reference]
Change-Id: Ic69a51ecaa5f15ccee049bb511e49425acdb23fe
Reviewed-on: http://review.couchbase.org/40170
Reviewed-by: Aliaksey Kandratsenka <[email protected]>
Tested-by: Aliaksey Kandratsenka <[email protected]>
| priv/public/js/logs.js | MB-11697: improved collect infos error handler | <ide><path>riv/public/js/logs.js
<ide>
<ide> var allActiveNodeBoxes;
<ide> var allNodeBoxes;
<del> var overlay;
<add> var overlayCollectInfoStartNewView;
<ide> var self = this;
<ide>
<ide> collectResultSectionSpinner.show();
<ide> collectForm.submit(function (e) {
<ide> e.preventDefault();
<ide>
<add> hideErrors();
<add>
<ide> var formValues = getCollectFormValues();
<ide>
<ide> if (formValues["upload"]) {
<del> var nonEmptyUpload = _.detect(("uploadHost customer ticket").split(" "), function (k) {
<del> return formValues[k] !== undefined;
<del> });
<del> if (!nonEmptyUpload) {
<del> var resp = JSON.stringify({"uploadHost": "upload host must be given if upload is selected",
<del> "customer": "customer must be given if upload is selected"});
<del> onError({responseText: resp});
<add> if (!formValues["customer"]) {
<add> showCollectInfoErrors("customer field must be given if upload is selected", "customer");
<add> }
<add> if (!formValues["uploadHost"]) {
<add> showCollectInfoErrors("upload host field must be given if upload is selected", "uploadHost");
<add> }
<add> if (!formValues["uploadHost"] || !formValues["customer"]) {
<ide> return;
<ide> }
<ide> }
<ide>
<ide> var overlayCollectForm = overlayWithSpinner(collectForm);
<ide>
<del> $.ajax({
<del> type: 'POST',
<del> url: '/controller/startLogsCollection',
<del> data: formValues,
<del> success: onSuccess,
<del> error: onError,
<del> complete: function () {
<del> overlayCollectForm.remove();
<del> saveButton.attr('disabled', false);
<del> }
<del> });
<del>
<del> function onSuccess() {
<del> overlay = overlayWithSpinner(collectInfoStartNewView);
<del> showResultViewBtn.hide();
<del> self.tasksCollectionInfoCell.changedSlot.subscribeOnce(function () {
<del> collectInfoViewNameCell.setValue("result");
<del> });
<del> recalculateTasksUri();
<del> hideErrors();
<del> }
<del>
<del> function onError(resp) {
<del> hideErrors();
<del> var errors = {};
<del> try {
<del> errors = JSON.parse(resp.responseText);
<del> } catch (e) {
<del> // nothing
<del> console.log("failed to parse json errors: ", e);
<del> }
<del> console.log("Got errors: ", errors);
<del> _.each(errors, function (value, key) {
<del> if (key != '_') {
<del> showErrors(key, value);
<del> } else {
<del> showErrors('generalCollectInfo', value);
<del> }
<del> });
<del> }
<add> jsonPostWithErrors('/controller/startLogsCollection', $.param(formValues), function (commonError, status, perFieldErrors) {
<add> overlayCollectForm.remove();
<add> saveButton.attr('disabled', false);
<add> if (status === 'success') {
<add> overlayCollectInfoStartNewView = overlayWithSpinner(collectInfoStartNewView);
<add> showResultViewBtn.hide();
<add> self.tasksCollectionInfoCell.changedSlot.subscribeOnce(function () {
<add> collectInfoViewNameCell.setValue("result");
<add> });
<add> recalculateTasksUri();
<add> } else {
<add> handleCollectInfoServersError(commonError, perFieldErrors);
<add> }
<add> });
<ide> });
<ide> uploadToCouchbase.change(function (e) {
<ide> $('input[type="text"]', uploadToForm).attr('disabled', !$(this).attr('checked'));
<ide> return params;
<ide> }
<ide>
<del> function showErrors(key, value) {
<add> function handleCollectInfoServersError(commonError, perFieldErrors) {
<add> _.each((!!commonError.length ? commonError : perFieldErrors), showCollectInfoErrors);
<add> }
<add> function showCollectInfoErrors(value, key) {
<add> key = key || 'generalCollectInfo';
<ide> $("#js_" + key + "_error").text(value).show();
<ide> $("#js_" + key + "_input").addClass("dynamic_input_error");
<ide> }
<ide> switchCollectionInfoView(isResultView, isCurrentlyRunning, isRunBefore);
<ide> collectResultSectionSpinner.hide();
<ide>
<del> if (overlay) {
<del> overlay.remove();
<add> if (overlayCollectInfoStartNewView) {
<add> overlayCollectInfoStartNewView.remove();
<ide> }
<ide> if (isResultView) {
<ide> renderResultView(collectionInfo); |
|
JavaScript | mit | 1d80c9538baa470d2d07061c94f1414a0511c032 | 0 | uber/riakpbc,nlf/riakpbc | var net = require('net'),
Stream = require('stream'),
protobuf = require('protobuf.js'),
butils = require('butils'),
through = require('through'),
path = require('path'),
_merge = require('./lib/merge');
var messageCodes = {
'0': 'RpbErrorResp',
'1': 'RpbPingReq',
'2': 'RpbPingResp',
'3': 'RpbGetClientIdReq',
'4': 'RpbGetClientIdResp',
'5': 'RpbSetClientIdReq',
'6': 'RpbSetClientIdResp',
'7': 'RpbGetServerInfoReq',
'8': 'RpbGetServerInfoResp',
'9': 'RpbGetReq',
'10': 'RpbGetResp',
'11': 'RpbPutReq',
'12': 'RpbPutResp',
'13': 'RpbDelReq',
'14': 'RpbDelResp',
'15': 'RpbListBucketsReq',
'16': 'RpbListBucketsResp',
'17': 'RpbListKeysReq',
'18': 'RpbListKeysResp',
'19': 'RpbGetBucketReq',
'20': 'RpbGetBucketResp',
'21': 'RpbSetBucketReq',
'22': 'RpbSetBucketResp',
'23': 'RpbMapRedReq',
'24': 'RpbMapRedResp',
'25': 'RpbIndexReq',
'26': 'RpbIndexResp',
'27': 'RpbSearchQueryReq',
'28': 'RpbSearchQueryResp',
// 1.4
'29': 'RpbResetBucketReq',
'30': 'RpbResetBucketResp',
'40': 'RpbCSBucketReq',
'41': 'RpbCSBucketResp',
'50': 'RpbCounterUpdateReq',
'51': 'RpbCounterUpdateResp',
'52': 'RpbCounterGetReq',
'53': 'RpbCounterGetResp',
};
Object.keys(messageCodes).forEach(function (key) {
messageCodes[messageCodes[key]] = Number(key);
});
function parseContent(item) {
if (!item.value || !item.content_type) {
return;
}
if (item.content_type.match(/^text\/\*/)) {
item.value = item.value.toString();
return;
}
if (item.content_type.toLowerCase() === 'application/json') {
item.value = JSON.parse(item.value.toString());
}
return item;
}
function RiakPBC(options) {
var self = this;
options = options || {};
self.host = options.host || '127.0.0.1';
self.port = options.port || 8087;
self.timeout = options.timeout || 1000;
self.bucket = options.bucket || undefined;
self.translator = protobuf.loadSchema(path.join(__dirname, './spec/riak_kv.proto'));
self.client = new net.Socket();
self.connected = false;
self.client.on('end', self.disconnect.bind(this));
self.client.on('error', self.disconnect.bind(this));
self.client.on('data', self._processPacket.bind(this));
self.paused = false;
self.queue = [];
self.reply = {};
self.resBuffers = [];
self.numBytesAwaiting = 0;
}
RiakPBC.prototype._splitPacket = function (pkt) {
var self = this;
var pos = 0, len;
if (self.numBytesAwaiting > 0) {
len = Math.min(pkt.length, self.numBytesAwaiting);
var oldBuf = self.resBuffers[self.resBuffers.length - 1];
var newBuf = new Buffer(oldBuf.length + len);
oldBuf.copy(newBuf, 0);
pkt.slice(0, len).copy(newBuf, oldBuf.length);
self.resBuffers[self.resBuffers.length - 1] = newBuf;
pos = len;
self.numBytesAwaiting -= len;
} else {
self.resBuffers = [];
}
while (pos < pkt.length) {
len = butils.readInt32(pkt, pos);
self.numBytesAwaiting = len + 4 - pkt.length;
self.resBuffers.push(pkt.slice(pos + 4, Math.min(pos + len + 4, pkt.length)));
pos += len + 4;
}
};
RiakPBC.prototype._processPacket = function (chunk) {
var self = this;
var stream = self.task.stream;
var err, response, packet, mc;
self._splitPacket(chunk);
if (self.numBytesAwaiting > 0) {
return;
}
processAllResBuffers(self.resBuffers);
function processAllResBuffers(resBuffers) {
resBuffers.forEach(processSingleResBuffer);
if (!self.task.expectMultiple || self.reply.done || mc === 'RpbErrorResp') {
if (err) {
self.reply = undefined;
}
var cb = self.task.callback;
self.task = undefined;
if (stream) {
stream.end();
} else {
cb(err, self.reply);
}
mc = undefined;
self.reply = {};
self.paused = false;
err = undefined;
self._processNext();
}
}
function processSingleResBuffer(packet) {
mc = messageCodes['' + packet[0]];
response = self.translator.decode(mc, packet.slice(1));
if (response.content && Array.isArray(response.content)) {
response.content.forEach(parseContent);
}
if (response.errmsg) {
err = new Error(response.errmsg);
err.code = response.errcode;
if (stream) {
stream.emit('error', err);
return;
}
}
if (stream && !response.done) {
stream.write(response);
}
if (stream) {
self.reply = response;
}
else {
self.reply = _merge(self.reply, response);
}
}
};
RiakPBC.prototype._processNext = function () {
var self = this;
if (self.queue.length && !self.paused) {
self.paused = true;
self.connect(function (err) {
self.task = self.queue.shift();
if (err) {
return self.task.callback(err);
}
self.client.write(self.task.message);
});
}
};
RiakPBC.prototype.makeRequest = function (type, data, callback, expectMultiple, streaming) {
var self = this,
buffer = this.translator.encode(type, data),
message = [],
stream;
if (typeof streaming === 'function') {
callback = streaming;
streaming = false;
}
if (streaming) {
stream = writableStream();
}
butils.writeInt32(message, buffer.length + 1);
butils.writeInt(message, messageCodes[type], 4);
message = message.concat(buffer);
self.queue.push({ message: new Buffer(message), callback: callback, expectMultiple: expectMultiple, stream: stream});
self._processNext();
return stream;
};
RiakPBC.prototype.getBuckets = function (callback) {
return this.makeRequest('RpbListBucketsReq', null, callback);
};
RiakPBC.prototype.getBucket = function (params, callback) {
this.makeRequest('RpbGetBucketReq', params, callback);
};
RiakPBC.prototype.setBucket = function (params, callback) {
this.makeRequest('RpbSetBucketReq', params, callback);
};
RiakPBC.prototype.resetBucket = function (params, callback) {
this.makeRequest('RpbResetBucketReq', params, callback);
};
RiakPBC.prototype.getKeys = function (params, streaming, callback) {
return this.makeRequest('RpbListKeysReq', params, callback, true, streaming);
};
RiakPBC.prototype.put = function (params, callback) {
this.makeRequest('RpbPutReq', params, callback);
};
RiakPBC.prototype.get = function (params, callback) {
this.makeRequest('RpbGetReq', params, callback);
};
RiakPBC.prototype.del = function (params, callback) {
this.makeRequest('RpbDelReq', params, callback);
};
RiakPBC.prototype.mapred = function (params, streaming, callback) {
var stream = this.makeRequest('RpbMapRedReq', params, callback, true, streaming);
if (!stream) {
return;
}
var parsedStream = parseMapReduceStream(stream);
return parsedStream;
};
RiakPBC.prototype.getCounter = function (params, callback) {
this.makeRequest('RpbCounterGetReq', params, callback);
};
RiakPBC.prototype.updateCounter = function (params, callback) {
this.makeRequest('RpbCounterUpdateReq', params, callback);
};
RiakPBC.prototype.getIndex = function (params, streaming, callback) {
if (typeof streaming === 'function') {
callback = streaming;
streaming = false;
}
if (streaming) {
var stream = this.makeRequest('RpbIndexReq', params, callback, true, streaming);
return stream;
} else {
this.makeRequest('RpbIndexReq', params, callback);
}
};
RiakPBC.prototype.search = function (params, callback) {
this.makeRequest('RpbSearchQueryReq', params, callback);
};
RiakPBC.prototype.getClientId = function (callback) {
this.makeRequest('RpbGetClientIdReq', null, callback);
};
RiakPBC.prototype.setClientId = function (params, callback) {
this.makeRequest('RpbSetClientIdReq', params, callback);
};
RiakPBC.prototype.getServerInfo = function (callback) {
this.makeRequest('RpbGetServerInfoReq', null, callback);
};
RiakPBC.prototype.ping = function (callback) {
this.makeRequest('RpbPingReq', null, callback);
};
RiakPBC.prototype.connect = function (callback) {
if (this.connected) {
return callback(null);
}
var self = this;
var timeoutGuard = setTimeout(function () {
callback(new Error('Connection timeout'));
}, self.timeout);
self.client.connect(self.port, self.host, function () {
clearTimeout(timeoutGuard);
self.connected = true;
callback(null);
});
};
RiakPBC.prototype.disconnect = function () {
if (!this.connected) {
return;
}
this.client.end();
this.connected = false;
if (this.task) {
this.queue.unshift(this.task);
this.task = undefined;
}
};
exports.createClient = function (options) {
return new RiakPBC(options);
};
function writableStream() {
var stream = through(function write(data) {
this.queue(data);
});
return stream;
}
function parseMapReduceStream(rawStream) {
var liner = new Stream.Transform({
objectMode: true
});
liner._transform = function (chunk, encoding, done) {
var response = chunk.response;
var json = JSON.parse(response);
var self = this;
json.forEach(function (row) {
self.push(row);
});
done();
};
rawStream.on('error', function (err) {
liner.emit('error', err);
});
rawStream.pipe(liner);
return liner;
}
| index.js | var net = require('net'),
Stream = require('stream'),
protobuf = require('protobuf.js'),
butils = require('butils'),
through = require('through'),
path = require('path'),
_merge = require('./lib/merge');
var messageCodes = {
'0': 'RpbErrorResp',
'1': 'RpbPingReq',
'2': 'RpbPingResp',
'3': 'RpbGetClientIdReq',
'4': 'RpbGetClientIdResp',
'5': 'RpbSetClientIdReq',
'6': 'RpbSetClientIdResp',
'7': 'RpbGetServerInfoReq',
'8': 'RpbGetServerInfoResp',
'9': 'RpbGetReq',
'10': 'RpbGetResp',
'11': 'RpbPutReq',
'12': 'RpbPutResp',
'13': 'RpbDelReq',
'14': 'RpbDelResp',
'15': 'RpbListBucketsReq',
'16': 'RpbListBucketsResp',
'17': 'RpbListKeysReq',
'18': 'RpbListKeysResp',
'19': 'RpbGetBucketReq',
'20': 'RpbGetBucketResp',
'21': 'RpbSetBucketReq',
'22': 'RpbSetBucketResp',
'23': 'RpbMapRedReq',
'24': 'RpbMapRedResp',
'25': 'RpbIndexReq',
'26': 'RpbIndexResp',
'27': 'RpbSearchQueryReq',
'28': 'RpbSearchQueryResp',
// 1.4
'29': 'RpbResetBucketReq',
'30': 'RpbResetBucketResp',
'40': 'RpbCSBucketReq',
'41': 'RpbCSBucketResp',
'50': 'RpbCounterUpdateReq',
'51': 'RpbCounterUpdateResp',
'52': 'RpbCounterGetReq',
'53': 'RpbCounterGetResp',
};
Object.keys(messageCodes).forEach(function (key) {
messageCodes[messageCodes[key]] = Number(key);
});
function parseContent(item) {
if (!item.value || !item.content_type) {
return;
}
if (item.content_type.match(/^text\/\*/)) {
item.value = item.value.toString();
return;
}
if (item.content_type.toLowerCase() === 'application/json') {
item.value = JSON.parse(item.value.toString());
}
return item;
}
function RiakPBC(options) {
var self = this;
options = options || {};
self.host = options.host || '127.0.0.1';
self.port = options.port || 8087;
self.timeout = options.timeout || 1000;
self.bucket = options.bucket || undefined;
self.translator = protobuf.loadSchema(path.join(__dirname, './spec/riak_kv.proto'));
self.client = new net.Socket();
self.connected = false;
self.client.on('end', self.disconnect.bind(this));
self.client.on('error', self.disconnect.bind(this));
self.client.on('data', self._processPacket.bind(this));
self.paused = false;
self.queue = [];
self.reply = {};
self.resBuffers = [];
self.numBytesAwaiting = 0;
}
RiakPBC.prototype._splitPacket = function (pkt) {
var self = this;
var pos = 0, len;
if (self.numBytesAwaiting > 0) {
len = Math.min(pkt.length, self.numBytesAwaiting);
var oldBuf = self.resBuffers[self.resBuffers.length - 1];
var newBuf = new Buffer(oldBuf.length + len);
oldBuf.copy(newBuf, 0);
pkt.slice(0, len).copy(newBuf, oldBuf.length);
self.resBuffers[self.resBuffers.length - 1] = newBuf;
pos = len;
self.numBytesAwaiting -= len;
} else {
self.resBuffers = [];
}
while (pos < pkt.length) {
len = butils.readInt32(pkt, pos);
self.numBytesAwaiting = len + 4 - pkt.length;
self.resBuffers.push(pkt.slice(pos + 4, Math.min(pos + len + 4, pkt.length)));
pos += len + 4;
}
};
RiakPBC.prototype._processPacket = function (chunk) {
var self = this;
var stream = self.task.stream;
var err, response, packet, mc;
self._splitPacket(chunk);
if (self.numBytesAwaiting > 0) {
return;
}
for (var i = 0, l = self.resBuffers.length; i < l; i++) {
packet = self.resBuffers[i];
mc = messageCodes['' + packet[0]];
response = self.translator.decode(mc, packet.slice(1));
if (response.content && Array.isArray(response.content)) {
response.content.forEach(parseContent);
}
if (response.errmsg) {
err = new Error(response.errmsg);
err.code = response.errcode;
if (stream) {
stream.emit('error', err);
return;
}
}
if (stream && !response.done) {
stream.write(response);
}
if (stream) {
self.reply = response;
}
else {
self.reply = _merge(self.reply, response);
}
}
if (!self.task.expectMultiple || self.reply.done || mc === 'RpbErrorResp') {
if (err) {
self.reply = undefined;
}
var cb = self.task.callback;
var emitter = self.task.emitter;
self.task = undefined;
if (stream) {
stream.end();
} else {
cb(err, self.reply);
}
mc = undefined;
self.reply = {};
self.paused = false;
err = undefined;
self._processNext();
}
};
RiakPBC.prototype._processNext = function () {
var self = this;
if (self.queue.length && !self.paused) {
self.paused = true;
self.connect(function (err) {
self.task = self.queue.shift();
if (err) {
return self.task.callback(err);
}
self.client.write(self.task.message);
});
}
};
RiakPBC.prototype.makeRequest = function (type, data, callback, expectMultiple, streaming) {
var self = this,
buffer = this.translator.encode(type, data),
message = [],
stream;
if (typeof streaming === 'function') {
callback = streaming;
streaming = false;
}
if (streaming) {
stream = writableStream();
}
butils.writeInt32(message, buffer.length + 1);
butils.writeInt(message, messageCodes[type], 4);
message = message.concat(buffer);
self.queue.push({ message: new Buffer(message), callback: callback, expectMultiple: expectMultiple, stream: stream});
self._processNext();
return stream;
};
RiakPBC.prototype.getBuckets = function (callback) {
return this.makeRequest('RpbListBucketsReq', null, callback);
};
RiakPBC.prototype.getBucket = function (params, callback) {
this.makeRequest('RpbGetBucketReq', params, callback);
};
RiakPBC.prototype.setBucket = function (params, callback) {
this.makeRequest('RpbSetBucketReq', params, callback);
};
RiakPBC.prototype.resetBucket = function (params, callback) {
this.makeRequest('RpbResetBucketReq', params, callback);
};
RiakPBC.prototype.getKeys = function (params, streaming, callback) {
return this.makeRequest('RpbListKeysReq', params, callback, true, streaming);
};
RiakPBC.prototype.put = function (params, callback) {
this.makeRequest('RpbPutReq', params, callback);
};
RiakPBC.prototype.get = function (params, callback) {
this.makeRequest('RpbGetReq', params, callback);
};
RiakPBC.prototype.del = function (params, callback) {
this.makeRequest('RpbDelReq', params, callback);
};
RiakPBC.prototype.mapred = function (params, streaming, callback) {
var stream = this.makeRequest('RpbMapRedReq', params, callback, true, streaming);
if (!stream) {
return;
}
var parsedStream = parseMapReduceStream(stream);
return parsedStream;
};
RiakPBC.prototype.getCounter = function (params, callback) {
this.makeRequest('RpbCounterGetReq', params, callback);
};
RiakPBC.prototype.updateCounter = function (params, callback) {
this.makeRequest('RpbCounterUpdateReq', params, callback);
};
RiakPBC.prototype.getIndex = function (params, streaming, callback) {
if (typeof streaming === 'function') {
callback = streaming;
streaming = false;
}
if (streaming) {
var stream = this.makeRequest('RpbIndexReq', params, callback, true, streaming);
return stream;
} else {
this.makeRequest('RpbIndexReq', params, callback);
}
};
RiakPBC.prototype.search = function (params, callback) {
this.makeRequest('RpbSearchQueryReq', params, callback);
};
RiakPBC.prototype.getClientId = function (callback) {
this.makeRequest('RpbGetClientIdReq', null, callback);
};
RiakPBC.prototype.setClientId = function (params, callback) {
this.makeRequest('RpbSetClientIdReq', params, callback);
};
RiakPBC.prototype.getServerInfo = function (callback) {
this.makeRequest('RpbGetServerInfoReq', null, callback);
};
RiakPBC.prototype.ping = function (callback) {
this.makeRequest('RpbPingReq', null, callback);
};
RiakPBC.prototype.connect = function (callback) {
if (this.connected) {
return callback(null);
}
var self = this;
var timeoutGuard = setTimeout(function () {
callback(new Error('Connection timeout'));
}, self.timeout);
self.client.connect(self.port, self.host, function () {
clearTimeout(timeoutGuard);
self.connected = true;
callback(null);
});
};
RiakPBC.prototype.disconnect = function () {
if (!this.connected) {
return;
}
this.client.end();
this.connected = false;
if (this.task) {
this.queue.unshift(this.task);
this.task = undefined;
}
};
exports.createClient = function (options) {
return new RiakPBC(options);
};
function writableStream() {
var stream = through(function write(data) {
this.queue(data);
});
return stream;
}
function parseMapReduceStream(rawStream) {
var liner = new Stream.Transform({
objectMode: true
});
liner._transform = function (chunk, encoding, done) {
var response = chunk.response;
var json = JSON.parse(response);
var self = this;
json.forEach(function (row) {
self.push(row);
});
done();
};
rawStream.on('error', function (err) {
liner.emit('error', err);
});
rawStream.pipe(liner);
return liner;
}
function parseMapRedStream() {
}
| Refactor: fix code smells.
Reduce complexity as suggessted by code climate.
| index.js | Refactor: fix code smells. | <ide><path>ndex.js
<ide> if (self.numBytesAwaiting > 0) {
<ide> return;
<ide> }
<del>
<del> for (var i = 0, l = self.resBuffers.length; i < l; i++) {
<del> packet = self.resBuffers[i];
<add> processAllResBuffers(self.resBuffers);
<add>
<add> function processAllResBuffers(resBuffers) {
<add> resBuffers.forEach(processSingleResBuffer);
<add> if (!self.task.expectMultiple || self.reply.done || mc === 'RpbErrorResp') {
<add> if (err) {
<add> self.reply = undefined;
<add> }
<add>
<add> var cb = self.task.callback;
<add> self.task = undefined;
<add> if (stream) {
<add> stream.end();
<add> } else {
<add> cb(err, self.reply);
<add> }
<add> mc = undefined;
<add> self.reply = {};
<add> self.paused = false;
<add> err = undefined;
<add> self._processNext();
<add> }
<add> }
<add>
<add> function processSingleResBuffer(packet) {
<ide> mc = messageCodes['' + packet[0]];
<del>
<ide> response = self.translator.decode(mc, packet.slice(1));
<ide> if (response.content && Array.isArray(response.content)) {
<ide> response.content.forEach(parseContent);
<ide> else {
<ide> self.reply = _merge(self.reply, response);
<ide> }
<del> }
<del> if (!self.task.expectMultiple || self.reply.done || mc === 'RpbErrorResp') {
<del> if (err) {
<del> self.reply = undefined;
<del> }
<del>
<del> var cb = self.task.callback;
<del> var emitter = self.task.emitter;
<del> self.task = undefined;
<del> if (stream) {
<del> stream.end();
<del> } else {
<del> cb(err, self.reply);
<del> }
<del> mc = undefined;
<del> self.reply = {};
<del> self.paused = false;
<del> err = undefined;
<del> self._processNext();
<ide> }
<ide> };
<ide>
<ide> rawStream.pipe(liner);
<ide> return liner;
<ide> }
<del>
<del>
<del>function parseMapRedStream() {
<del>
<del>} |
|
JavaScript | bsd-3-clause | 86f7683a27cd860ef08c6084dd7100a77d77d903 | 0 | tijptjik/mycroft,tijptjik/mycroft,tijptjik/mycroft | /**
* Bootstrap validate
* English lang module
*/
$.bt_validate.fn = {
'require' : function(value) { return (value != null) && (value != '')},
'required' : function(value) { return (value != null) && (value != '')},
'email' : function(value) { return /^[a-z0-9-_\.]+@[a-z0-9-_\.]+\.[a-z]{2,4}$/.test(value.toLowerCase()) },
'www' : function(value) { return /^(http:\/\/)|(https:\/\/)[a-z0-9\/\.-_]+\.[a-z]{2,4}$/.test(value) },
'date' : function(value) { return /^[\d]{2}\/[\d]{2}\/[\d]{4}$/.test(value) },
'time' : function(value) { return /^[\d]{2}:[\d]{2}(:{0,1}[\d]{0,2})$/.test(value) },
'datetime' : function(value) { return /^[\d]{2}\/[\d]{2}\/[\d]{4} [\d]{2}:[\d]{2}:{0,1}[\d]{0,2}$/.test(value) },
'number' : function(value) { return /^[\d]+$/.test(value) },
'float' : function(value) { return /^([\d]+)|(\d]+\.[\d]+)$/.test(value) },
'equal' : function(value, eq_value) { return (value == eq_value); },
'min' : function(value, min) { return Number(value) >= min },
'max' : function(value, max) { return Number(value) <= max },
'between' : function(value, min, max) { return (Number(value) >= min) && (Number(value) <= max)},
'length_min' : function(value, min) { return value.length >= min },
'length_max' : function(value, max) { return value.length <= max },
'custom_pass_eq' : function(value) { return $('#password1').val() == $('#password2').val()},
'length_between' : function(value, min, max) { return (value.length >= min) && (value.length <= max)}
}
$.bt_validate.text = {
'require' : 'Enter your e-mail address to receive the lectures',
'required' : 'The value can not be empty',
'email' : 'The value is not valid email',
'www' : 'The value is not valid http string',
'date' : 'The value is not valid date',
'time' : 'The value is not valid time',
'datetime' : 'The value is not valid datetime',
'number' : 'The value is not valid number',
'float' : 'The value is not valid floating point number',
'equal' : 'The value must be equal to "%1"',
'min' : 'The value must be equal or greater than %1',
'max' : 'The value must be equal or less than %1',
'between' : 'The value must be between %1 and %2',
'length_min' : 'The length of the value must be equal or greater than %1',
'length_max' : 'The length of the value must be equal or less than %1',
'length_between' : 'The length of the value must be between %1 and %2',
'custom_pass_eq' : 'The passwords are not equal'
}
| mycroft/base/static/js/libs/bootstrap/bootstrap-validate.en.js | /**
* Bootstrap validate
* English lang module
*/
$.bt_validate.fn = {
'require' : function(value) { return (value != null) && (value != '')},
'required' : function(value) { return (value != null) && (value != '')},
'email' : function(value) { return /^[a-z0-9-_\.]+@[a-z0-9-_\.]+\.[a-z]{2,4}$/.test(value) },
'www' : function(value) { return /^(http:\/\/)|(https:\/\/)[a-z0-9\/\.-_]+\.[a-z]{2,4}$/.test(value) },
'date' : function(value) { return /^[\d]{2}\/[\d]{2}\/[\d]{4}$/.test(value) },
'time' : function(value) { return /^[\d]{2}:[\d]{2}(:{0,1}[\d]{0,2})$/.test(value) },
'datetime' : function(value) { return /^[\d]{2}\/[\d]{2}\/[\d]{4} [\d]{2}:[\d]{2}:{0,1}[\d]{0,2}$/.test(value) },
'number' : function(value) { return /^[\d]+$/.test(value) },
'float' : function(value) { return /^([\d]+)|(\d]+\.[\d]+)$/.test(value) },
'equal' : function(value, eq_value) { return (value == eq_value); },
'min' : function(value, min) { return Number(value) >= min },
'max' : function(value, max) { return Number(value) <= max },
'between' : function(value, min, max) { return (Number(value) >= min) && (Number(value) <= max)},
'length_min' : function(value, min) { return value.length >= min },
'length_max' : function(value, max) { return value.length <= max },
'custom_pass_eq' : function(value) { return $('#password1').val() == $('#password2').val()},
'length_between' : function(value, min, max) { return (value.length >= min) && (value.length <= max)}
}
$.bt_validate.text = {
'require' : 'Enter your e-mail address to receive the lectures',
'required' : 'The value can not be empty',
'email' : 'The value is not valid email',
'www' : 'The value is not valid http string',
'date' : 'The value is not valid date',
'time' : 'The value is not valid time',
'datetime' : 'The value is not valid datetime',
'number' : 'The value is not valid number',
'float' : 'The value is not valid floating point number',
'equal' : 'The value must be equal to "%1"',
'min' : 'The value must be equal or greater than %1',
'max' : 'The value must be equal or less than %1',
'between' : 'The value must be between %1 and %2',
'length_min' : 'The length of the value must be equal or greater than %1',
'length_max' : 'The length of the value must be equal or less than %1',
'length_between' : 'The length of the value must be between %1 and %2',
'custom_pass_eq' : 'The passwords are not equal'
}
| Accept Uppercase e-mails
| mycroft/base/static/js/libs/bootstrap/bootstrap-validate.en.js | Accept Uppercase e-mails | <ide><path>ycroft/base/static/js/libs/bootstrap/bootstrap-validate.en.js
<ide> $.bt_validate.fn = {
<ide> 'require' : function(value) { return (value != null) && (value != '')},
<ide> 'required' : function(value) { return (value != null) && (value != '')},
<del> 'email' : function(value) { return /^[a-z0-9-_\.]+@[a-z0-9-_\.]+\.[a-z]{2,4}$/.test(value) },
<add> 'email' : function(value) { return /^[a-z0-9-_\.]+@[a-z0-9-_\.]+\.[a-z]{2,4}$/.test(value.toLowerCase()) },
<ide> 'www' : function(value) { return /^(http:\/\/)|(https:\/\/)[a-z0-9\/\.-_]+\.[a-z]{2,4}$/.test(value) },
<ide> 'date' : function(value) { return /^[\d]{2}\/[\d]{2}\/[\d]{4}$/.test(value) },
<ide> 'time' : function(value) { return /^[\d]{2}:[\d]{2}(:{0,1}[\d]{0,2})$/.test(value) }, |
|
Java | apache-2.0 | 3beb89ce8564ced899fea48062e9009662791f31 | 0 | knighthunter09/cw-omnibus,ajju4455/cw-omnibus,hamidsn/cw-omnibus,ryandh/cw-omnibus,a-ankitpatel/cw-omnibus,immuvijay/cw-omnibus,iconodo/cw-omnibus,HaiderAliG/cw-omnibus,jorgereina1986/cw-omnibus,JGeovani/cw-omnibus,oussemaAr/cw-omnibus,IUHHUI/cw-omnibus,ajju4455/cw-omnibus,LG67/cw-omnibus,jvvlives2005/cw-omnibus,atishagrawal/cw-omnibus,juanmendez/cw-omnibus,c00240488/cw-omnibus,knighthunter09/cw-omnibus,jvvlives2005/cw-omnibus,ryandh/cw-omnibus,rjhonsl/cw-omnibus,poojawins/cw-omnibus,aschworer/cw-omnibus,hamidsn/cw-omnibus,ajju4455/cw-omnibus,kinghy2302/cw-omnibus,prashant31191/cw-omnibus,LG67/cw-omnibus,peterdocter/cw-omnibus,JGeovani/cw-omnibus,gkavyakurpad/cw-omnibus,knighthunter09/cw-omnibus,VinayakDeshpande11/cw-omnibus,c00240488/cw-omnibus,JGeovani/cw-omnibus,atishagrawal/cw-omnibus,weikipeng/cw-omnibus,lexiaoyao20/cw-omnibus,c00240488/cw-omnibus,alexsh/cw-omnibus,HaiderAliG/cw-omnibus,jorgereina1986/cw-omnibus,c00240488/cw-omnibus,c00240488/cw-omnibus,ranjith068/cw-omnibus,MingxuanChen/cw-omnibus,Jumshaid/empublite,commonsguy/cw-omnibus,poojawins/cw-omnibus,jojobando/cw-omnibus,raghunandankavi2010/cw-omnibus,tianyong2/cw-omnibus,aeron1sh/cw-omnibus,mangel99/cw-omnibus,juanmendez/cw-omnibus,xyzy/cw-omnibus,xyzy/cw-omnibus,juanmendez/cw-omnibus,ranjith068/cw-omnibus,Jumshaid/empublite,tianyong2/cw-omnibus,hkngoc/cw-omnibus,maduhu/cw-omnibus,andrea9a/cw-omnibus,esavard/cw-omnibus,jorgereina1986/cw-omnibus,esavard/cw-omnibus,HasanAliKaraca/cw-omnibus,suclike/cw-omnibus,raghunandankavi2010/cw-omnibus,andy199609/cw-omnibus,aeron1sh/cw-omnibus,jorgereina1986/cw-omnibus,superboonie/cw-omnibus,oussemaAr/cw-omnibus,beyondbycyx/cw-omnibus,alexsh/cw-omnibus,superboonie/cw-omnibus,atishagrawal/cw-omnibus,tianyong2/cw-omnibus,commonsguy/cw-omnibus,ranjith068/cw-omnibus,mangel99/cw-omnibus,IUHHUI/cw-omnibus,oussemaAr/cw-omnibus,LG67/cw-omnibus,aschworer/cw-omnibus,commonsguy/cw-omnibus,AkechiNEET/cw-omnibus,a-ankitpatel/cw-omnibus,peterdocter/cw-omnibus,kinghy2302/cw-omnibus,gkavyakurpad/cw-omnibus,jorgereina1986/cw-omnibus,raghunandankavi2010/cw-omnibus,ajju4455/cw-omnibus,iconodo/cw-omnibus,prashant31191/cw-omnibus,mangel99/cw-omnibus,iconodo/cw-omnibus,oussemaAr/cw-omnibus,HaiderAliG/cw-omnibus,VinayakDeshpande11/cw-omnibus,HasanAliKaraca/cw-omnibus,yuriysych/cw-omnibus,commonsguy/cw-omnibus,hkngoc/cw-omnibus,mangel99/cw-omnibus,tianyong2/cw-omnibus,hamidsn/cw-omnibus,juanmendez/cw-omnibus,VinayakDeshpande11/cw-omnibus,beyondbycyx/cw-omnibus,speedyGonzales/cw-omnibus,aeron1sh/cw-omnibus,onloner/cw-omnibus,jasonzhong/cw-omnibus,AkechiNEET/cw-omnibus,JGeovani/cw-omnibus,raghunandankavi2010/cw-omnibus,janzoner/cw-omnibus,ryandh/cw-omnibus,hkngoc/cw-omnibus,maduhu/cw-omnibus,rjhonsl/cw-omnibus,raghunandankavi2010/cw-omnibus,ranjith068/cw-omnibus,alexsh/cw-omnibus,ryandh/cw-omnibus,hamidsn/cw-omnibus,EvidenceKiller/cw-omnibus,HasanAliKaraca/cw-omnibus,knighthunter09/cw-omnibus,andy199609/cw-omnibus,xyzy/cw-omnibus,iconodo/cw-omnibus,maharsh007/cw-omnibus,rickywo/cw-omnibus,a-ankitpatel/cw-omnibus,aschworer/cw-omnibus,gkavyakurpad/cw-omnibus,aschworer/cw-omnibus,andy199609/cw-omnibus,jvvlives2005/cw-omnibus,rickywo/cw-omnibus,kinghy2302/cw-omnibus,JGeovani/cw-omnibus,hamidsn/cw-omnibus,superboonie/cw-omnibus,jojobando/cw-omnibus,LG67/cw-omnibus,LG67/cw-omnibus,onloner/cw-omnibus,juanmendez/cw-omnibus,rjhonsl/cw-omnibus,aschworer/cw-omnibus,maduhu/cw-omnibus,suclike/cw-omnibus,treejames/cw-omnibus,a-ankitpatel/cw-omnibus,janzoner/cw-omnibus,immuvijay/cw-omnibus,jasonzhong/cw-omnibus,hkngoc/cw-omnibus,VinayakDeshpande11/cw-omnibus,lexiaoyao20/cw-omnibus,peterdocter/cw-omnibus,andrea9a/cw-omnibus,andrea9a/cw-omnibus,rickywo/cw-omnibus,andrea9a/cw-omnibus,ajju4455/cw-omnibus,IUHHUI/cw-omnibus,HaiderAliG/cw-omnibus,janzoner/cw-omnibus,andrea9a/cw-omnibus,JGeovani/cw-omnibus,commonsguy/cw-omnibus,kinghy2302/cw-omnibus,beyondbycyx/cw-omnibus,gkavyakurpad/cw-omnibus,MingxuanChen/cw-omnibus,jvvlives2005/cw-omnibus,ryandh/cw-omnibus,speedyGonzales/cw-omnibus,treejames/cw-omnibus,maharsh007/cw-omnibus,janzoner/cw-omnibus,VinayakDeshpande11/cw-omnibus,treejames/cw-omnibus,speedyGonzales/cw-omnibus,itasanb/cw-omnibus,PavelKniha/cw-omnibus,PavelKniha/cw-omnibus,kinghy2302/cw-omnibus,EvidenceKiller/cw-omnibus,DaveKavanagh/cw-omnibus,tianyong2/cw-omnibus,itasanb/cw-omnibus,IUHHUI/cw-omnibus,rjhonsl/cw-omnibus,MingxuanChen/cw-omnibus,poojawins/cw-omnibus,iconodo/cw-omnibus,IUHHUI/cw-omnibus,janzoner/cw-omnibus,kinghy2302/cw-omnibus,speedyGonzales/cw-omnibus,jojobando/cw-omnibus,commonsguy/cw-omnibus,jojobando/cw-omnibus,ranjith068/cw-omnibus,HasanAliKaraca/cw-omnibus,immuvijay/cw-omnibus,mangel99/cw-omnibus,a-ankitpatel/cw-omnibus,MingxuanChen/cw-omnibus,poojawins/cw-omnibus,jojobando/cw-omnibus,prashant31191/cw-omnibus,peterdocter/cw-omnibus,jasonzhong/cw-omnibus,onloner/cw-omnibus,PavelKniha/cw-omnibus,Jumshaid/empublite,knighthunter09/cw-omnibus,gkavyakurpad/cw-omnibus,poojawins/cw-omnibus,janzoner/cw-omnibus,iconodo/cw-omnibus,itasanb/cw-omnibus,AkechiNEET/cw-omnibus,HasanAliKaraca/cw-omnibus,lexiaoyao20/cw-omnibus,commonsguy/cw-omnibus,Jumshaid/empublite,rickywo/cw-omnibus,suclike/cw-omnibus,rjhonsl/cw-omnibus,maduhu/cw-omnibus,weikipeng/cw-omnibus,maharsh007/cw-omnibus,tianyong2/cw-omnibus,superboonie/cw-omnibus,jasonzhong/cw-omnibus,c00240488/cw-omnibus,LG67/cw-omnibus,PavelKniha/cw-omnibus,EvidenceKiller/cw-omnibus,jojobando/cw-omnibus,jvvlives2005/cw-omnibus,superboonie/cw-omnibus,suclike/cw-omnibus,rickywo/cw-omnibus,ranjith068/cw-omnibus,DaveKavanagh/cw-omnibus,knighthunter09/cw-omnibus,superboonie/cw-omnibus,yuriysych/cw-omnibus,itasanb/cw-omnibus,yuriysych/cw-omnibus,jasonzhong/cw-omnibus,onloner/cw-omnibus,treejames/cw-omnibus,gkavyakurpad/cw-omnibus,IUHHUI/cw-omnibus,andy199609/cw-omnibus,andy199609/cw-omnibus,VinayakDeshpande11/cw-omnibus,jorgereina1986/cw-omnibus,AkechiNEET/cw-omnibus,hkngoc/cw-omnibus,oussemaAr/cw-omnibus,treejames/cw-omnibus,jvvlives2005/cw-omnibus,maharsh007/cw-omnibus,maharsh007/cw-omnibus,EvidenceKiller/cw-omnibus,MingxuanChen/cw-omnibus,mangel99/cw-omnibus,hamidsn/cw-omnibus,suclike/cw-omnibus,hkngoc/cw-omnibus,juanmendez/cw-omnibus,alexsh/cw-omnibus,PavelKniha/cw-omnibus,maduhu/cw-omnibus,prashant31191/cw-omnibus,esavard/cw-omnibus,immuvijay/cw-omnibus,aeron1sh/cw-omnibus,weikipeng/cw-omnibus,speedyGonzales/cw-omnibus,onloner/cw-omnibus,immuvijay/cw-omnibus,EvidenceKiller/cw-omnibus,aschworer/cw-omnibus,beyondbycyx/cw-omnibus,peterdocter/cw-omnibus,alexsh/cw-omnibus,itasanb/cw-omnibus,raghunandankavi2010/cw-omnibus,andy199609/cw-omnibus,yuriysych/cw-omnibus,andrea9a/cw-omnibus,treejames/cw-omnibus,MingxuanChen/cw-omnibus,EvidenceKiller/cw-omnibus,atishagrawal/cw-omnibus,HasanAliKaraca/cw-omnibus,DaveKavanagh/cw-omnibus,lexiaoyao20/cw-omnibus,atishagrawal/cw-omnibus,oussemaAr/cw-omnibus,prashant31191/cw-omnibus,suclike/cw-omnibus,atishagrawal/cw-omnibus,alexsh/cw-omnibus,HaiderAliG/cw-omnibus,esavard/cw-omnibus,itasanb/cw-omnibus,peterdocter/cw-omnibus,aeron1sh/cw-omnibus,PavelKniha/cw-omnibus,weikipeng/cw-omnibus,HaiderAliG/cw-omnibus,beyondbycyx/cw-omnibus,xyzy/cw-omnibus,lexiaoyao20/cw-omnibus,ryandh/cw-omnibus,DaveKavanagh/cw-omnibus,poojawins/cw-omnibus,beyondbycyx/cw-omnibus,AkechiNEET/cw-omnibus,DaveKavanagh/cw-omnibus,speedyGonzales/cw-omnibus,esavard/cw-omnibus,rjhonsl/cw-omnibus,xyzy/cw-omnibus,prashant31191/cw-omnibus,Jumshaid/empublite,xyzy/cw-omnibus,lexiaoyao20/cw-omnibus,maduhu/cw-omnibus,Jumshaid/empublite,a-ankitpatel/cw-omnibus,onloner/cw-omnibus,esavard/cw-omnibus,jasonzhong/cw-omnibus,alexsh/cw-omnibus,AkechiNEET/cw-omnibus,yuriysych/cw-omnibus,yuriysych/cw-omnibus,rickywo/cw-omnibus,weikipeng/cw-omnibus,ajju4455/cw-omnibus,maharsh007/cw-omnibus,DaveKavanagh/cw-omnibus,weikipeng/cw-omnibus | /***
Copyright (c) 2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.tabfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class TabFragmentDemoActivity extends SherlockFragmentActivity
implements TabListener {
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private CharSequence[] models=new CharSequence[10];
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
if (state != null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
ActionBar bar=getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i=0; i < 10; i++) {
bar.addTab(bar.newTab().setText("Tab #" + String.valueOf(i + 1))
.setTabListener(this).setTag(i));
}
if (state != null) {
bar.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
}
@Override
public void onSaveInstanceState(Bundle state) {
state.putCharSequenceArray(KEY_MODELS, models);
state.putInt(KEY_POSITION,
getSupportActionBar().getSelectedNavigationIndex());
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
int i=((Integer)tab.getTag()).intValue();
ft.replace(android.R.id.content,
EditorFragment.newInstance(i, models[i]));
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
int i=((Integer)tab.getTag()).intValue();
EditorFragment frag=
(EditorFragment)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag != null) {
models[i]=frag.getText();
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// unused
}
} | ActionBar/TabFragmentDemo/src/com/commonsware/android/tabfrag/TabFragmentDemoActivity.java | /***
Copyright (c) 2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.tabfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class TabFragmentDemoActivity extends
SherlockFragmentActivity implements TabListener {
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private CharSequence[] models=new CharSequence[10];
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
if (state!=null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
ActionBar bar=getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i=0;i<10;i++) {
bar.addTab(bar.newTab()
.setText("Tab #"+String.valueOf(i+1))
.setTabListener(this)
.setTag(i));
}
if (state!=null) {
bar.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
}
@Override
public void onSaveInstanceState(Bundle state) {
state.putCharSequenceArray(KEY_MODELS, models);
state.putInt(KEY_POSITION, getSupportActionBar().getSelectedNavigationIndex());
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
int i=((Integer)tab.getTag()).intValue();
ft.replace(android.R.id.content, EditorFragment.newInstance(i, models[i]));
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
int i=((Integer)tab.getTag()).intValue();
EditorFragment frag=(EditorFragment)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag!=null) {
models[i]=frag.getText();
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// unused
}
} | formatting
| ActionBar/TabFragmentDemo/src/com/commonsware/android/tabfrag/TabFragmentDemoActivity.java | formatting | <ide><path>ctionBar/TabFragmentDemo/src/com/commonsware/android/tabfrag/TabFragmentDemoActivity.java
<ide> import com.actionbarsherlock.app.ActionBar.TabListener;
<ide> import com.actionbarsherlock.app.SherlockFragmentActivity;
<ide>
<del>public class TabFragmentDemoActivity extends
<del> SherlockFragmentActivity implements TabListener {
<add>public class TabFragmentDemoActivity extends SherlockFragmentActivity
<add> implements TabListener {
<ide> private static final String KEY_MODELS="models";
<ide> private static final String KEY_POSITION="position";
<ide> private CharSequence[] models=new CharSequence[10];
<del>
<add>
<ide> @Override
<ide> public void onCreate(Bundle state) {
<ide> super.onCreate(state);
<ide>
<del> if (state!=null) {
<add> if (state != null) {
<ide> models=state.getCharSequenceArray(KEY_MODELS);
<ide> }
<del>
<add>
<ide> ActionBar bar=getSupportActionBar();
<ide> bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
<ide>
<del> for (int i=0;i<10;i++) {
<del> bar.addTab(bar.newTab()
<del> .setText("Tab #"+String.valueOf(i+1))
<del> .setTabListener(this)
<del> .setTag(i));
<add> for (int i=0; i < 10; i++) {
<add> bar.addTab(bar.newTab().setText("Tab #" + String.valueOf(i + 1))
<add> .setTabListener(this).setTag(i));
<ide> }
<ide>
<del> if (state!=null) {
<add> if (state != null) {
<ide> bar.setSelectedNavigationItem(state.getInt(KEY_POSITION));
<ide> }
<ide> }
<del>
<add>
<ide> @Override
<ide> public void onSaveInstanceState(Bundle state) {
<ide> state.putCharSequenceArray(KEY_MODELS, models);
<del> state.putInt(KEY_POSITION, getSupportActionBar().getSelectedNavigationIndex());
<add> state.putInt(KEY_POSITION,
<add> getSupportActionBar().getSelectedNavigationIndex());
<ide> }
<ide>
<ide> @Override
<ide> public void onTabSelected(Tab tab, FragmentTransaction ft) {
<ide> int i=((Integer)tab.getTag()).intValue();
<del>
<del> ft.replace(android.R.id.content, EditorFragment.newInstance(i, models[i]));
<add>
<add> ft.replace(android.R.id.content,
<add> EditorFragment.newInstance(i, models[i]));
<ide> }
<ide>
<ide> @Override
<ide> public void onTabUnselected(Tab tab, FragmentTransaction ft) {
<ide> int i=((Integer)tab.getTag()).intValue();
<del> EditorFragment frag=(EditorFragment)getSupportFragmentManager().findFragmentById(android.R.id.content);
<del>
<del> if (frag!=null) {
<add> EditorFragment frag=
<add> (EditorFragment)getSupportFragmentManager().findFragmentById(android.R.id.content);
<add>
<add> if (frag != null) {
<ide> models[i]=frag.getText();
<ide> }
<ide> } |
|
Java | apache-2.0 | 29c4c035ae07347a78fa7901dcada8727dcdddd2 | 0 | hungdoan2/phonegap-googlemaps-plugin,hitoci/phonegap-googlemaps-plugin,rynomster/cordova-plugin-googlemaps,LouisMazel/cordova-plugin-googlemaps,fabriziogiordano/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,hungdoan2/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,elwahid/plugin.google.maps,arilsonkarmo/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,rynomster/cordova-plugin-googlemaps,Nipher/phonegap-googlemaps-plugin,LouisMazel/cordova-plugin-googlemaps,blanedaze/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,iDay/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,Jerome2606/phonegap-googlemaps-plugin,otreva/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,hitoci/phonegap-googlemaps-plugin,hungdoan2/phonegap-googlemaps-plugin,hitoci/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,edivancamargo/phonegap-googlemaps-plugin,edivancamargo/phonegap-googlemaps-plugin,snoopconsulting/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,edivancamargo/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,mapsplugin/cordova-plugin-googlemaps,cabify/cordova-plugin-googlemaps,quiuquio/cordova-plugin-googlemaps,mapsplugin/cordova-plugin-googlemaps,otreva/phonegap-googlemaps-plugin,roberthovhannisyan/phonegap-googlemaps-plugin,elwahid/plugin.google.maps,arilsonkarmo/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,cabify/cordova-plugin-googlemaps,snoopconsulting/phonegap-googlemaps-plugin,wf9a5m75/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,smcpjames/cordova-plugin-googlemaps,fabriziogiordano/phonegap-googlemaps-plugin,fabriziogiordano/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,pinkbike/phonegap-googlemaps-plugin,denisbabineau/phonegap-googlemaps-plugin,iDay/phonegap-googlemaps-plugin,otreva/phonegap-googlemaps-plugin,LouisMazel/cordova-plugin-googlemaps,Jerome2606/phonegap-googlemaps-plugin,otreva/phonegap-googlemaps-plugin,Jerome2606/phonegap-googlemaps-plugin,denisbabineau/phonegap-googlemaps-plugin,CPlus/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,alexislg2/phonegap-googlemaps-plugin,denisbabineau/cordova-plugin-googlemaps,edivancamargo/phonegap-googlemaps-plugin,dukhanov/cordova-plugin-googlemaps,dukhanov/cordova-plugin-googlemaps,matsprea/phonegap-googlemaps-plugin,quiuquio/cordova-plugin-googlemaps,blanedaze/phonegap-googlemaps-plugin,roberthovhannisyan/phonegap-googlemaps-plugin,Nipher/phonegap-googlemaps-plugin,smcpjames/cordova-plugin-googlemaps,denisbabineau/phonegap-googlemaps-plugin,arilsonkarmo/phonegap-googlemaps-plugin,athiradandira/phonegap-googlemaps-plugin,fabriziogiordano/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,wf9a5m75/phonegap-googlemaps-plugin,pinkbike/phonegap-googlemaps-plugin,blanedaze/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,eandresblasco/phonegap-googlemaps-plugin,piotrbelina/phonegap-googlemaps-plugin,rynomster/cordova-plugin-googlemaps,denisbabineau/cordova-plugin-googlemaps,eandresblasco/phonegap-googlemaps-plugin,alexislg2/phonegap-googlemaps-plugin,EmilianStankov/cordova-plugin-googlemaps,denisbabineau/cordova-plugin-googlemaps,hitoci/phonegap-googlemaps-plugin,joewoodhouse/phonegap-googlemaps-plugin,joewoodhouse/phonegap-googlemaps-plugin,quiuquio/cordova-plugin-googlemaps,Nipher/phonegap-googlemaps-plugin,matsprea/phonegap-googlemaps-plugin,snoopconsulting/phonegap-googlemaps-plugin,joewoodhouse/phonegap-googlemaps-plugin,wolf-s/phonegap-googlemaps-plugin,smcpjames/cordova-plugin-googlemaps,iDay/phonegap-googlemaps-plugin,Jerome2606/phonegap-googlemaps-plugin,Skysurfer0110/phonegap-googlemaps-plugin,snoopconsulting/phonegap-googlemaps-plugin,dukhanov/cordova-plugin-googlemaps,hungdoan2/phonegap-googlemaps-plugin,roberthovhannisyan/phonegap-googlemaps-plugin,pinkbike/phonegap-googlemaps-plugin,elwahid/plugin.google.maps,alexislg2/phonegap-googlemaps-plugin,elwahid/plugin.google.maps,wf9a5m75/phonegap-googlemaps-plugin,Nipher/phonegap-googlemaps-plugin,mapsplugin/cordova-plugin-googlemaps,cabify/cordova-plugin-googlemaps,matsprea/phonegap-googlemaps-plugin | package plugin.google.maps;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class AsyncKmlParser extends AsyncTask<String, Void, Bundle> {
private XmlPullParser parser;
private GoogleMaps mMapCtrl;
private Activity mActivity;
private CallbackContext mCallback;
private enum KML_TAG {
style,
stylemap,
linestyle,
polystyle,
linestring,
outerboundaryis,
placemark,
point,
polygon,
pair,
multigeometry,
key,
styleurl,
color,
width,
fill,
name,
description,
icon,
href,
coordinates
};
public AsyncKmlParser(Activity activity, GoogleMaps mapCtrl, CallbackContext callbackContext) {
mCallback = callbackContext;
mMapCtrl = mapCtrl;
mActivity = activity;
try {
parser = XmlPullParserFactory.newInstance().newPullParser();
} catch (Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
@Override
protected Bundle doInBackground(String... params) {
Bundle kmlData = null;
try {
InputStream inputStream = null;
String urlStr = params[0];
if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
Log.e("Map", urlStr);
URL url = new URL(urlStr);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
http.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
http.addRequestProperty("User-Agent", "Mozilla");
http.addRequestProperty("Referer", "google.com");
http.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
boolean redirect = false;
// normally, 3xx is redirect
int status = http.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
if (redirect) {
// get redirect url from "location" header field
String newUrl = http.getHeaderField("Location");
// get the cookie if need, for login
String cookies = http.getHeaderField("Set-Cookie");
// open the new connnection again
http = (HttpURLConnection) new URL(newUrl).openConnection();
http.setRequestProperty("Cookie", cookies);
http.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
http.addRequestProperty("User-Agent", "Mozilla");
http.addRequestProperty("Referer", "google.com");
}
inputStream = http.getInputStream();
} else {
inputStream = mActivity.getResources().getAssets().open(urlStr);
}
parser.setInput(inputStream, null);
kmlData = parseXML(parser);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return kmlData;
}
private Bundle getStyleById(Bundle styles, String styleId) {
Bundle style = null;
Bundle tmpBundle;
String tagName, tmp;
ArrayList<Bundle> bundleList;
Iterator<Bundle> bundleIterator;
if (styles.containsKey(styleId)) {
style = styles.getBundle(styleId);
tagName = style.getString("tagName");
if ("stylemap".equals(tagName)) {
bundleList = style.getParcelableArrayList("children");
bundleIterator = bundleList.iterator();
while(bundleIterator.hasNext()) {
tmpBundle = bundleIterator.next();
if ("normal".equals(tmpBundle.getString("key")) &&
tmpBundle.containsKey("styleurl")) {
tmp = tmpBundle.getString("styleurl");
style = styles.getBundle(tmp);
break;
}
}
}
}
return style;
}
protected void onPostExecute(Bundle parseResult) {
if (parseResult == null) {
mCallback.error("KML Parse error");
return;
}
Bundle styles = parseResult.getBundle("styles");
ArrayList<Bundle> placeMarks = parseResult.getParcelableArrayList("placeMarks");
float density = Resources.getSystem().getDisplayMetrics().density;
Bundle options;
JSONObject optionsJSON;
String tmp, tagName;
Bundle node, style, childNode;
ArrayList<Bundle> bundleList;
ArrayList<Bundle> children;
ArrayList<Bundle> latLngList;
Iterator<Bundle> iterator = placeMarks.iterator();
Iterator<Bundle> bundleIterator;
Iterator<Bundle> childrenIterator;
while(iterator.hasNext()) {
node = iterator.next();
children = node.getParcelableArrayList("children");
if (children == null) {
continue;
}
childrenIterator = children.iterator();
while(childrenIterator.hasNext()) {
childNode = childrenIterator.next();
tagName = childNode.getString("tagName");
switch(KML_TAG.valueOf(tagName)) {
case point:
//-----------------
// Marker
//-----------------
options = new Bundle();
//position
latLngList = childNode.getParcelableArrayList("coordinates");
options.putBundle("position", latLngList.get(0));
//title
tmp = node.getString("name");
if (node.containsKey("description")) {
tmp += "\n\n" + node.getString("description");
}
options.putString("title", tmp);
//icon
if (node.containsKey("styleurl")) {
tmp = node.getString("styleurl");
} else {
tmp = "#__default__";
}
style = getStyleById(styles, tmp);
if (style != null) {
bundleList = style.getParcelableArrayList("children");
bundleIterator = bundleList.iterator();
while(bundleIterator.hasNext()) {
style = bundleIterator.next();
tagName = style.getString("tagName");
if ("icon".equals(tagName)) {;
options.putString("icon", style.getString("href"));
}
}
}
this.implementToMap("Marker", options);
break;
case linestring:
//-----------------
// Polyline
//-----------------
//points
options = new Bundle();
latLngList = childNode.getParcelableArrayList("coordinates");
options.putParcelableArrayList("points", latLngList);
options.putBoolean("visible", true);
options.putBoolean("geodesic", true);
//Bundle -> JSON
optionsJSON = PluginUtil.Bundle2Json(options);
//color, width
if (node.containsKey("styleurl")) {
tmp = node.getString("styleurl");
} else {
tmp = "#__default__";
}
style = getStyleById(styles, tmp);
if (style != null) {
bundleList = style.getParcelableArrayList("children");
bundleIterator = bundleList.iterator();
while(bundleIterator.hasNext()) {
style = bundleIterator.next();
tagName = style.getString("tagName");
switch(KML_TAG.valueOf(tagName)) {
case linestyle:
if (style.containsKey("color")) {
try {
optionsJSON.put("color", kmlColor2PluginColor(style.getString("color")));
} catch (JSONException e) {}
}
if (style.containsKey("width")) {
try {
optionsJSON.put("width", (int) (Integer.parseInt(style.getString("width")) * density));
} catch (Exception e) {}
}
break;
}
}
}
this.implementToMap("Polyline", optionsJSON);
break;
case polygon:
//-----------------
// Polygon
//-----------------
children = childNode.getParcelableArrayList("children");
childNode = children.get(0);
options = new Bundle();
latLngList = childNode.getParcelableArrayList("coordinates");
options.putParcelableArrayList("points", latLngList);
options.putBoolean("visible", true);
options.putInt("strokeWidth", 0);
//Bundle -> JSON
optionsJSON = PluginUtil.Bundle2Json(options);
if (node.containsKey("styleurl")) {
tmp = node.getString("styleurl");
} else {
tmp = "#__default__";
}
style = getStyleById(styles, tmp);
if (style != null) {
bundleList = style.getParcelableArrayList("children");
bundleIterator = bundleList.iterator();
while(bundleIterator.hasNext()) {
style = bundleIterator.next();
tagName = style.getString("tagName");
switch(KML_TAG.valueOf(tagName)) {
case polystyle:
if (style.containsKey("color")) {
try {
optionsJSON.put("fillColor", kmlColor2PluginColor(style.getString("color")));
} catch (JSONException e) {}
}
break;
case linestyle:
if (style.containsKey("color")) {
try {
optionsJSON.put("strokeColor", kmlColor2PluginColor(style.getString("color")));
} catch (JSONException e) {};
}
if (style.containsKey("width")) {
try {
optionsJSON.put("strokeWidth", (int)Float.parseFloat(style.getString("width")) * density);
} catch (Exception e) {}
}
break;
}
}
} else {
Log.e("client", "--" + style + " is null");
}
this.implementToMap("Polygon", optionsJSON);
break;
}
}
}
this.mCallback.success();
}
private void implementToMap(String className, JSONObject optionsJSON) {
JSONArray params = new JSONArray();
params.put(className + ".create" + className);
params.put(optionsJSON);
CallbackContext callback2 = new CallbackContext("kmlOverlay-create" + className, this.mMapCtrl.webView);
try {
mMapCtrl.execute("exec", params, callback2);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void implementToMap(String className, Bundle options) {
// Load the class plugin
this.implementToMap(className, PluginUtil.Bundle2Json(options));
}
private JSONArray kmlColor2PluginColor(String colorStr) {
JSONArray rgba = new JSONArray();
for (int i = 2; i < 8; i+=2) {
rgba.put(Integer.parseInt(colorStr.substring(i, i + 2), 16));
}
rgba.put(Integer.parseInt(colorStr.substring(0, 2), 16));
return rgba;
}
private Bundle parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
{
ArrayList<Bundle> placeMarks = new ArrayList<Bundle>();
int eventType = parser.getEventType();
Bundle currentNode = null;
Bundle result = new Bundle();
ArrayList<Bundle> nodeStack = new ArrayList<Bundle>();
Bundle styles = new Bundle();
Bundle parentNode = null;
ArrayList<Bundle> pairList = null;
KML_TAG kmlTag = null;
String tagName = null;
String tmp;
int nodeIndex = 0;
while (eventType != XmlPullParser.END_DOCUMENT){
tagName = null;
kmlTag = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
tagName = parser.getName().toLowerCase();
Log.i("Map", "tagName-->" + tagName);
try {
kmlTag = KML_TAG.valueOf(tagName);
} catch(Exception e) {}
if (kmlTag == null) {
eventType = parser.next();
continue;
}
switch (kmlTag) {
case stylemap:
case style:
//push
nodeStack.add(currentNode);
currentNode = new Bundle();
currentNode.putString("tagName", tagName);
tmp = parser.getAttributeValue(null, "id");
if (tmp == null) {
tmp = "__default__";
}
currentNode.putString("id", tmp);
pairList = new ArrayList<Bundle>();
break;
case multigeometry:
if (currentNode != null) {
//push
nodeStack.add(currentNode);
currentNode = new Bundle();
currentNode.putString("tagName", tagName);
pairList = new ArrayList<Bundle>();
}
break;
case placemark:
currentNode = new Bundle();
currentNode.putString("tagName", tagName);
pairList = null;
break;
case linestyle:
case polystyle:
case pair:
case point:
case linestring:
case outerboundaryis:
case polygon:
case icon:
if (currentNode != null) {
//push
nodeStack.add(currentNode);
currentNode = new Bundle();
currentNode.putString("tagName", tagName);
}
break;
case href:
case key:
case styleurl:
case name:
case width:
case color:
case fill:
case description:
if (currentNode != null) {
currentNode.putString(tagName, parser.nextText());
}
break;
case coordinates:
if (currentNode != null) {
ArrayList<Bundle> latLngList = new ArrayList<Bundle>();
String txt = parser.nextText();
String lines[] = txt.split("[\\n\\s]");
String tmpArry[];
Bundle latLng;
int i;
for (i = 0; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("[^0-9,.\\-]", "");
if ("".equals(lines[i]) == false) {
tmpArry = lines[i].split(",");
latLng = new Bundle();
latLng.putFloat("lat", Float.parseFloat(tmpArry[1]));
latLng.putFloat("lng", Float.parseFloat(tmpArry[0]));
latLngList.add(latLng);
}
}
currentNode.putParcelableArrayList(tagName, latLngList);
}
break;
default:
break;
}
break;
case XmlPullParser.END_TAG:
if (currentNode != null) {
tagName = parser.getName().toLowerCase();
kmlTag = null;
try {
kmlTag = KML_TAG.valueOf(tagName);
} catch(Exception e) {}
if (kmlTag == null) {
eventType = parser.next();
continue;
}
switch (kmlTag) {
case stylemap:
case style:
currentNode.putParcelableArrayList("children", pairList);
styles.putBundle("#" + currentNode.getString("id"), currentNode);
//pop
nodeIndex = nodeStack.size() - 1;
parentNode = nodeStack.get(nodeIndex);
nodeStack.remove(nodeIndex);
currentNode = parentNode;
break;
case multigeometry:
if (currentNode != null) {
//pop
nodeIndex = nodeStack.size() - 1;
parentNode = nodeStack.get(nodeIndex);
parentNode.putParcelableArrayList("children", pairList);
parentNode.putString("tagName", tagName);
nodeStack.remove(nodeIndex);
currentNode = parentNode;
pairList = null;
}
break;
case placemark:
placeMarks.add(currentNode);
currentNode = null;
break;
case pair:
case linestyle:
case polystyle:
if (currentNode != null) {
pairList.add(currentNode);
//pop
nodeIndex = nodeStack.size() - 1;
parentNode = nodeStack.get(nodeIndex);
nodeStack.remove(nodeIndex);
currentNode = parentNode;
}
break;
case icon:
case point:
case outerboundaryis:
case linestring:
case coordinates:
case polygon:
if (currentNode != null) {
//pop
nodeIndex = nodeStack.size() - 1;
parentNode = nodeStack.get(nodeIndex);
nodeStack.remove(nodeIndex);
if (parentNode.containsKey("children")) {
pairList = parentNode.getParcelableArrayList("children");
pairList.add(currentNode);
parentNode.putParcelableArrayList("children", pairList);
} else {
pairList = new ArrayList<Bundle>();
pairList.add(currentNode);
parentNode.putParcelableArrayList("children", pairList);
}
currentNode = parentNode;
}
break;
default:
break;
}
}
break;
}
eventType = parser.next();
}
result.putParcelableArrayList("placeMarks", placeMarks);
result.putBundle("styles", styles);
return result;
}
}
| platforms/android/src/plugin/google/maps/AsyncKmlParser.java | package plugin.google.maps;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class AsyncKmlParser extends AsyncTask<String, Void, Bundle> {
private XmlPullParser parser;
private GoogleMaps mMapCtrl;
private Activity mActivity;
private CallbackContext mCallback;
private enum KML_TAG {
style,
stylemap,
linestyle,
polystyle,
linestring,
outerboundaryis,
placemark,
point,
polygon,
pair,
multigeometry,
key,
styleurl,
color,
width,
fill,
name,
description,
icon,
href,
coordinates
};
public AsyncKmlParser(Activity activity, GoogleMaps mapCtrl, CallbackContext callbackContext) {
mCallback = callbackContext;
mMapCtrl = mapCtrl;
mActivity = activity;
try {
parser = XmlPullParserFactory.newInstance().newPullParser();
} catch (Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
@Override
protected Bundle doInBackground(String... params) {
Bundle kmlData = null;
try {
InputStream inputStream = null;
String urlStr = params[0];
if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
Log.e("Map", urlStr);
URL url = new URL(urlStr);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
http.connect();
inputStream = http.getInputStream();
} else {
inputStream = mActivity.getResources().getAssets().open(urlStr);
}
parser.setInput(inputStream, null);
kmlData = parseXML(parser);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return kmlData;
}
private Bundle getStyleById(Bundle styles, String styleId) {
Bundle style = null;
Bundle tmpBundle;
String tagName, tmp;
ArrayList<Bundle> bundleList;
Iterator<Bundle> bundleIterator;
if (styles.containsKey(styleId)) {
style = styles.getBundle(styleId);
tagName = style.getString("tagName");
if ("stylemap".equals(tagName)) {
bundleList = style.getParcelableArrayList("children");
bundleIterator = bundleList.iterator();
while(bundleIterator.hasNext()) {
tmpBundle = bundleIterator.next();
if ("normal".equals(tmpBundle.getString("key")) &&
tmpBundle.containsKey("styleurl")) {
tmp = tmpBundle.getString("styleurl");
style = styles.getBundle(tmp);
break;
}
}
}
}
return style;
}
protected void onPostExecute(Bundle parseResult) {
if (parseResult == null) {
mCallback.error("KML Parse error");
return;
}
Bundle styles = parseResult.getBundle("styles");
ArrayList<Bundle> placeMarks = parseResult.getParcelableArrayList("placeMarks");
float density = Resources.getSystem().getDisplayMetrics().density;
Bundle options;
JSONObject optionsJSON;
String tmp, tagName;
Bundle node, style, childNode;
ArrayList<Bundle> bundleList;
ArrayList<Bundle> children;
ArrayList<Bundle> latLngList;
Iterator<Bundle> iterator = placeMarks.iterator();
Iterator<Bundle> bundleIterator;
Iterator<Bundle> childrenIterator;
while(iterator.hasNext()) {
node = iterator.next();
children = node.getParcelableArrayList("children");
if (children == null) {
continue;
}
childrenIterator = children.iterator();
while(childrenIterator.hasNext()) {
childNode = childrenIterator.next();
tagName = childNode.getString("tagName");
switch(KML_TAG.valueOf(tagName)) {
case point:
//-----------------
// Marker
//-----------------
options = new Bundle();
//position
latLngList = childNode.getParcelableArrayList("coordinates");
options.putBundle("position", latLngList.get(0));
//title
tmp = node.getString("name");
if (node.containsKey("description")) {
tmp += "\n\n" + node.getString("description");
}
options.putString("title", tmp);
//icon
if (node.containsKey("styleurl")) {
tmp = node.getString("styleurl");
} else {
tmp = "#__default__";
}
style = getStyleById(styles, tmp);
if (style != null) {
bundleList = style.getParcelableArrayList("children");
bundleIterator = bundleList.iterator();
while(bundleIterator.hasNext()) {
style = bundleIterator.next();
tagName = style.getString("tagName");
if ("icon".equals(tagName)) {;
options.putString("icon", style.getString("href"));
}
}
}
this.implementToMap("Marker", options);
break;
case linestring:
//-----------------
// Polyline
//-----------------
//points
options = new Bundle();
latLngList = childNode.getParcelableArrayList("coordinates");
options.putParcelableArrayList("points", latLngList);
options.putBoolean("visible", true);
options.putBoolean("geodesic", true);
//Bundle -> JSON
optionsJSON = PluginUtil.Bundle2Json(options);
//color, width
if (node.containsKey("styleurl")) {
tmp = node.getString("styleurl");
} else {
tmp = "#__default__";
}
style = getStyleById(styles, tmp);
if (style != null) {
bundleList = style.getParcelableArrayList("children");
bundleIterator = bundleList.iterator();
while(bundleIterator.hasNext()) {
style = bundleIterator.next();
tagName = style.getString("tagName");
switch(KML_TAG.valueOf(tagName)) {
case linestyle:
if (style.containsKey("color")) {
try {
optionsJSON.put("color", kmlColor2PluginColor(style.getString("color")));
} catch (JSONException e) {}
}
if (style.containsKey("width")) {
try {
optionsJSON.put("width", (int) (Integer.parseInt(style.getString("width")) * density));
} catch (Exception e) {}
}
break;
}
}
}
this.implementToMap("Polyline", optionsJSON);
break;
case polygon:
//-----------------
// Polygon
//-----------------
children = childNode.getParcelableArrayList("children");
childNode = children.get(0);
options = new Bundle();
latLngList = childNode.getParcelableArrayList("coordinates");
options.putParcelableArrayList("points", latLngList);
options.putBoolean("visible", true);
options.putInt("strokeWidth", 0);
//Bundle -> JSON
optionsJSON = PluginUtil.Bundle2Json(options);
if (node.containsKey("styleurl")) {
tmp = node.getString("styleurl");
} else {
tmp = "#__default__";
}
style = getStyleById(styles, tmp);
if (style != null) {
bundleList = style.getParcelableArrayList("children");
bundleIterator = bundleList.iterator();
while(bundleIterator.hasNext()) {
style = bundleIterator.next();
tagName = style.getString("tagName");
switch(KML_TAG.valueOf(tagName)) {
case polystyle:
if (style.containsKey("color")) {
try {
optionsJSON.put("fillColor", kmlColor2PluginColor(style.getString("color")));
} catch (JSONException e) {}
}
break;
case linestyle:
if (style.containsKey("color")) {
try {
optionsJSON.put("strokeColor", kmlColor2PluginColor(style.getString("color")));
} catch (JSONException e) {};
}
if (style.containsKey("width")) {
try {
optionsJSON.put("strokeWidth", (int)Float.parseFloat(style.getString("width")) * density);
} catch (Exception e) {}
}
break;
}
}
} else {
Log.e("client", "--" + style + " is null");
}
this.implementToMap("Polygon", optionsJSON);
break;
}
}
}
this.mCallback.success();
}
private void implementToMap(String className, JSONObject optionsJSON) {
JSONArray params = new JSONArray();
params.put(className + ".create" + className);
params.put(optionsJSON);
CallbackContext callback2 = new CallbackContext("kmlOverlay-create" + className, this.mMapCtrl.webView);
try {
mMapCtrl.execute("exec", params, callback2);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void implementToMap(String className, Bundle options) {
// Load the class plugin
this.implementToMap(className, PluginUtil.Bundle2Json(options));
}
private JSONArray kmlColor2PluginColor(String colorStr) {
JSONArray rgba = new JSONArray();
for (int i = 2; i < 8; i+=2) {
rgba.put(Integer.parseInt(colorStr.substring(i, i + 2), 16));
}
rgba.put(Integer.parseInt(colorStr.substring(0, 2), 16));
return rgba;
}
private Bundle parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
{
ArrayList<Bundle> placeMarks = new ArrayList<Bundle>();
int eventType = parser.getEventType();
Bundle currentNode = null;
Bundle result = new Bundle();
ArrayList<Bundle> nodeStack = new ArrayList<Bundle>();
Bundle styles = new Bundle();
Bundle parentNode = null;
ArrayList<Bundle> pairList = null;
KML_TAG kmlTag = null;
String tagName = null;
String tmp;
int nodeIndex = 0;
while (eventType != XmlPullParser.END_DOCUMENT){
tagName = null;
kmlTag = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
tagName = parser.getName().toLowerCase();
Log.i("Map", "tagName-->" + tagName);
try {
kmlTag = KML_TAG.valueOf(tagName);
} catch(Exception e) {}
if (kmlTag == null) {
eventType = parser.next();
continue;
}
switch (kmlTag) {
case stylemap:
case style:
//push
nodeStack.add(currentNode);
currentNode = new Bundle();
currentNode.putString("tagName", tagName);
tmp = parser.getAttributeValue(null, "id");
if (tmp == null) {
tmp = "__default__";
}
currentNode.putString("id", tmp);
pairList = new ArrayList<Bundle>();
break;
case multigeometry:
if (currentNode != null) {
//push
nodeStack.add(currentNode);
currentNode = new Bundle();
currentNode.putString("tagName", tagName);
pairList = new ArrayList<Bundle>();
}
break;
case placemark:
currentNode = new Bundle();
currentNode.putString("tagName", tagName);
pairList = null;
break;
case linestyle:
case polystyle:
case pair:
case point:
case linestring:
case outerboundaryis:
case polygon:
case icon:
if (currentNode != null) {
//push
nodeStack.add(currentNode);
currentNode = new Bundle();
currentNode.putString("tagName", tagName);
}
break;
case href:
case key:
case styleurl:
case name:
case width:
case color:
case fill:
case description:
if (currentNode != null) {
currentNode.putString(tagName, parser.nextText());
}
break;
case coordinates:
if (currentNode != null) {
ArrayList<Bundle> latLngList = new ArrayList<Bundle>();
String txt = parser.nextText();
String lines[] = txt.split("[\\n\\s]");
String tmpArry[];
Bundle latLng;
int i;
for (i = 0; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("[^0-9,.\\-]", "");
if ("".equals(lines[i]) == false) {
tmpArry = lines[i].split(",");
latLng = new Bundle();
latLng.putFloat("lat", Float.parseFloat(tmpArry[1]));
latLng.putFloat("lng", Float.parseFloat(tmpArry[0]));
latLngList.add(latLng);
}
}
currentNode.putParcelableArrayList(tagName, latLngList);
}
break;
default:
break;
}
break;
case XmlPullParser.END_TAG:
if (currentNode != null) {
tagName = parser.getName().toLowerCase();
kmlTag = null;
try {
kmlTag = KML_TAG.valueOf(tagName);
} catch(Exception e) {}
if (kmlTag == null) {
eventType = parser.next();
continue;
}
switch (kmlTag) {
case stylemap:
case style:
currentNode.putParcelableArrayList("children", pairList);
styles.putBundle("#" + currentNode.getString("id"), currentNode);
//pop
nodeIndex = nodeStack.size() - 1;
parentNode = nodeStack.get(nodeIndex);
nodeStack.remove(nodeIndex);
currentNode = parentNode;
break;
case multigeometry:
if (currentNode != null) {
//pop
nodeIndex = nodeStack.size() - 1;
parentNode = nodeStack.get(nodeIndex);
parentNode.putParcelableArrayList("children", pairList);
parentNode.putString("tagName", tagName);
nodeStack.remove(nodeIndex);
currentNode = parentNode;
pairList = null;
}
break;
case placemark:
placeMarks.add(currentNode);
currentNode = null;
break;
case pair:
case linestyle:
case polystyle:
if (currentNode != null) {
pairList.add(currentNode);
//pop
nodeIndex = nodeStack.size() - 1;
parentNode = nodeStack.get(nodeIndex);
nodeStack.remove(nodeIndex);
currentNode = parentNode;
}
break;
case icon:
case point:
case outerboundaryis:
case linestring:
case coordinates:
case polygon:
if (currentNode != null) {
//pop
nodeIndex = nodeStack.size() - 1;
parentNode = nodeStack.get(nodeIndex);
nodeStack.remove(nodeIndex);
if (parentNode.containsKey("children")) {
pairList = parentNode.getParcelableArrayList("children");
pairList.add(currentNode);
parentNode.putParcelableArrayList("children", pairList);
} else {
pairList = new ArrayList<Bundle>();
pairList.add(currentNode);
parentNode.putParcelableArrayList("children", pairList);
}
currentNode = parentNode;
}
break;
default:
break;
}
}
break;
}
eventType = parser.next();
}
result.putParcelableArrayList("placeMarks", placeMarks);
result.putBundle("styles", styles);
return result;
}
}
| (Android) kmlOverlay allows http url
| platforms/android/src/plugin/google/maps/AsyncKmlParser.java | (Android) kmlOverlay allows http url | <ide><path>latforms/android/src/plugin/google/maps/AsyncKmlParser.java
<ide> URL url = new URL(urlStr);
<ide> HttpURLConnection http = (HttpURLConnection)url.openConnection();
<ide> http.setRequestMethod("GET");
<del> http.connect();
<add> http.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
<add> http.addRequestProperty("User-Agent", "Mozilla");
<add> http.addRequestProperty("Referer", "google.com");
<add> http.setInstanceFollowRedirects(true);
<add> HttpURLConnection.setFollowRedirects(true);
<add>
<add> boolean redirect = false;
<add> // normally, 3xx is redirect
<add> int status = http.getResponseCode();
<add> if (status != HttpURLConnection.HTTP_OK) {
<add> if (status == HttpURLConnection.HTTP_MOVED_TEMP
<add> || status == HttpURLConnection.HTTP_MOVED_PERM
<add> || status == HttpURLConnection.HTTP_SEE_OTHER)
<add> redirect = true;
<add> }
<add> if (redirect) {
<add>
<add> // get redirect url from "location" header field
<add> String newUrl = http.getHeaderField("Location");
<add>
<add> // get the cookie if need, for login
<add> String cookies = http.getHeaderField("Set-Cookie");
<add>
<add> // open the new connnection again
<add> http = (HttpURLConnection) new URL(newUrl).openConnection();
<add> http.setRequestProperty("Cookie", cookies);
<add> http.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
<add> http.addRequestProperty("User-Agent", "Mozilla");
<add> http.addRequestProperty("Referer", "google.com");
<add> }
<add>
<ide> inputStream = http.getInputStream();
<ide> } else {
<ide> inputStream = mActivity.getResources().getAssets().open(urlStr); |
|
Java | agpl-3.0 | 09632afb78c6796c5d4d05400c7d82eda3e611c0 | 0 | Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge | /* Copyright (C) 2015-2019 Andreas Böhler, Andreas Shimokawa, Avamander,
Carsten Pfeiffer, Daniel Dakhno, Daniele Gobbetti, Daniel Hauck, Dikay900,
Frank Slezak, ivanovlev, João Paulo Barraca, José Rebelo, Julien Pivotto,
Kasha, keeshii, Martin, Matthieu Baerts, Nephiel, Sebastian Kranz, Sergey
Trofimov, Steffen Liebergeld, Taavi Eomäe, Uwe Hermann
This file is part of Gadgetbridge.
Gadgetbridge is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Gadgetbridge is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package nodomain.freeyourgadget.gadgetbridge.service;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.activities.HeartRateUtils;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceCoordinator;
import nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmClockReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.BluetoothConnectReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.BluetoothPairingRequestReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.CMWeatherReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.CalendarReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.LineageOsWeatherReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.MusicPlaybackReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.OmniJawsObserver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.PebbleReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.PhoneCallReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.SMSReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.TimeChangeReceiver;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationType;
import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec;
import nodomain.freeyourgadget.gadgetbridge.service.receivers.AutoConnectIntervalReceiver;
import nodomain.freeyourgadget.gadgetbridge.service.receivers.GBAutoFetchReceiver;
import nodomain.freeyourgadget.gadgetbridge.util.DeviceHelper;
import nodomain.freeyourgadget.gadgetbridge.util.EmojiConverter;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
import nodomain.freeyourgadget.gadgetbridge.util.GBPrefs;
import nodomain.freeyourgadget.gadgetbridge.util.Prefs;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_ADD_CALENDAREVENT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_APP_CONFIGURE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_APP_REORDER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_CALLSTATE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_CONNECT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_DELETEAPP;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_DELETE_CALENDAREVENT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_DELETE_NOTIFICATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_DISCONNECT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_ENABLE_HEARTRATE_SLEEP_SUPPORT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_ENABLE_REALTIME_HEARTRATE_MEASUREMENT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_ENABLE_REALTIME_STEPS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_FETCH_RECORDED_DATA;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_FIND_DEVICE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_HEARTRATE_TEST;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_INSTALL;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_NOTIFICATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_READ_CONFIGURATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_REQUEST_APPINFO;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_REQUEST_DEVICEINFO;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_REQUEST_SCREENSHOT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_RESET;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SEND_CONFIGURATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SEND_WEATHER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SETCANNEDMESSAGES;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SETMUSICINFO;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SETMUSICSTATE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SETTIME;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_ALARMS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_CONSTANT_VIBRATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_FM_FREQUENCY;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_HEARTRATE_MEASUREMENT_INTERVAL;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_LED_COLOR;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_START;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_STARTAPP;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_TEST_NEW_FUNCTION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_ALARMS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_CONFIG;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_CONFIG_ID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_START;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_UUID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_BOOLEAN_ENABLE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_DESCRIPTION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_ID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_LOCATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_TIMESTAMP;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_TITLE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_TYPE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALL_COMMAND;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALL_DISPLAYNAME;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALL_PHONENUMBER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CANNEDMESSAGES;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CANNEDMESSAGES_TYPE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CONFIG;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CONNECT_FIRST_TIME;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_FIND_START;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_FM_FREQUENCY;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_INTERVAL_SECONDS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_LED_COLOR;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_ALBUM;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_ARTIST;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_POSITION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_RATE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_REPEAT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_SHUFFLE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_STATE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_TRACK;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_TRACKCOUNT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_TRACKNR;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_ACTIONS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_BODY;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_FLAGS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_ID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_PEBBLE_COLOR;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_PHONENUMBER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_SENDER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_SOURCEAPPID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_SOURCENAME;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_SUBJECT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_TITLE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_TYPE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_RECORDED_DATA_TYPES;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_RESET_FLAGS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_URI;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_VIBRATION_INTENSITY;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_WEATHER;
public class DeviceCommunicationService extends Service implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(DeviceCommunicationService.class);
@SuppressLint("StaticFieldLeak") // only used for test cases
private static DeviceSupportFactory DEVICE_SUPPORT_FACTORY = null;
private boolean mStarted = false;
private DeviceSupportFactory mFactory;
private GBDevice mGBDevice = null;
private DeviceSupport mDeviceSupport;
private DeviceCoordinator mCoordinator = null;
private PhoneCallReceiver mPhoneCallReceiver = null;
private SMSReceiver mSMSReceiver = null;
private PebbleReceiver mPebbleReceiver = null;
private MusicPlaybackReceiver mMusicPlaybackReceiver = null;
private TimeChangeReceiver mTimeChangeReceiver = null;
private BluetoothConnectReceiver mBlueToothConnectReceiver = null;
private BluetoothPairingRequestReceiver mBlueToothPairingRequestReceiver = null;
private AlarmClockReceiver mAlarmClockReceiver = null;
private GBAutoFetchReceiver mGBAutoFetchReceiver = null;
private AutoConnectIntervalReceiver mAutoConnectInvervalReceiver= null;
private AlarmReceiver mAlarmReceiver = null;
private CalendarReceiver mCalendarReceiver = null;
private CMWeatherReceiver mCMWeatherReceiver = null;
private LineageOsWeatherReceiver mLineageOsWeatherReceiver = null;
private OmniJawsObserver mOmniJawsObserver = null;
private final String[] mMusicActions = {
"com.android.music.metachanged",
"com.android.music.playstatechanged",
"com.android.music.queuechanged",
"com.android.music.playbackcomplete",
"net.sourceforge.subsonic.androidapp.EVENT_META_CHANGED",
"com.maxmpz.audioplayer.TPOS_SYNC",
"com.maxmpz.audioplayer.STATUS_CHANGED",
"com.maxmpz.audioplayer.PLAYING_MODE_CHANGED",
"com.spotify.music.metadatachanged",
"com.spotify.music.playbackstatechanged"
};
/**
* For testing!
*
* @param factory
*/
public static void setDeviceSupportFactory(DeviceSupportFactory factory) {
DEVICE_SUPPORT_FACTORY = factory;
}
public DeviceCommunicationService() {
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (GBDevice.ACTION_DEVICE_CHANGED.equals(action)) {
GBDevice device = intent.getParcelableExtra(GBDevice.EXTRA_DEVICE);
if (mGBDevice != null && mGBDevice.equals(device)) {
mGBDevice = device;
mCoordinator = DeviceHelper.getInstance().getCoordinator(device);
boolean enableReceivers = mDeviceSupport != null && (mDeviceSupport.useAutoConnect() || mGBDevice.isInitialized());
setReceiversEnableState(enableReceivers, mGBDevice.isInitialized(), mCoordinator);
} else {
LOG.error("Got ACTION_DEVICE_CHANGED from unexpected device: " + device);
}
}
}
};
@Override
public void onCreate() {
LOG.debug("DeviceCommunicationService is being created");
super.onCreate();
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(GBDevice.ACTION_DEVICE_CHANGED));
mFactory = getDeviceSupportFactory();
if (hasPrefs()) {
getPrefs().getPreferences().registerOnSharedPreferenceChangeListener(this);
}
}
private DeviceSupportFactory getDeviceSupportFactory() {
if (DEVICE_SUPPORT_FACTORY != null) {
return DEVICE_SUPPORT_FACTORY;
}
return new DeviceSupportFactory(this);
}
@Override
public synchronized int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
LOG.info("no intent");
return START_NOT_STICKY;
}
String action = intent.getAction();
boolean firstTime = intent.getBooleanExtra(EXTRA_CONNECT_FIRST_TIME, false);
if (action == null) {
LOG.info("no action");
return START_NOT_STICKY;
}
LOG.debug("Service startcommand: " + action);
if (!action.equals(ACTION_START) && !action.equals(ACTION_CONNECT)) {
if (!mStarted) {
// using the service before issuing ACTION_START
LOG.info("Must start service with " + ACTION_START + " or " + ACTION_CONNECT + " before using it: " + action);
return START_NOT_STICKY;
}
if (mDeviceSupport == null || (!isInitialized() && !action.equals(ACTION_DISCONNECT) && (!mDeviceSupport.useAutoConnect() || isConnected()))) {
// trying to send notification without valid Bluetooth connection
if (mGBDevice != null) {
// at least send back the current device state
mGBDevice.sendDeviceUpdateIntent(this);
}
return START_STICKY;
}
}
// when we get past this, we should have valid mDeviceSupport and mGBDevice instances
Prefs prefs = getPrefs();
switch (action) {
case ACTION_START:
start();
break;
case ACTION_CONNECT:
start(); // ensure started
GBDevice gbDevice = intent.getParcelableExtra(GBDevice.EXTRA_DEVICE);
String btDeviceAddress = null;
if (gbDevice == null) {
if (prefs != null) { // may be null in test cases
btDeviceAddress = prefs.getString("last_device_address", null);
if (btDeviceAddress != null) {
gbDevice = DeviceHelper.getInstance().findAvailableDevice(btDeviceAddress, this);
}
}
} else {
btDeviceAddress = gbDevice.getAddress();
}
boolean autoReconnect = GBPrefs.AUTO_RECONNECT_DEFAULT;
if (prefs != null && prefs.getPreferences() != null) {
prefs.getPreferences().edit().putString("last_device_address", btDeviceAddress).apply();
autoReconnect = getGBPrefs().getAutoReconnect();
}
if (gbDevice != null && !isConnecting() && !isConnected()) {
setDeviceSupport(null);
try {
DeviceSupport deviceSupport = mFactory.createDeviceSupport(gbDevice);
if (deviceSupport != null) {
setDeviceSupport(deviceSupport);
if (firstTime) {
deviceSupport.connectFirstTime();
} else {
deviceSupport.setAutoReconnect(autoReconnect);
deviceSupport.connect();
}
} else {
GB.toast(this, getString(R.string.cannot_connect, "Can't create device support"), Toast.LENGTH_SHORT, GB.ERROR);
}
} catch (Exception e) {
GB.toast(this, getString(R.string.cannot_connect, e.getMessage()), Toast.LENGTH_SHORT, GB.ERROR, e);
setDeviceSupport(null);
}
} else if (mGBDevice != null) {
// send an update at least
mGBDevice.sendDeviceUpdateIntent(this);
}
break;
default:
if (mDeviceSupport == null || mGBDevice == null) {
LOG.warn("device support:" + mDeviceSupport + ", device: " + mGBDevice + ", aborting");
} else {
handleAction(intent, action, prefs);
}
break;
}
return START_STICKY;
}
/**
* @param text original text
* @return 'text' or a new String without non supported chars like emoticons, etc.
*/
private String sanitizeNotifText(String text) {
if (text == null || text.length() == 0)
return text;
text = mDeviceSupport.customStringFilter(text);
if (!mCoordinator.supportsUnicodeEmojis()) {
return EmojiConverter.convertUnicodeEmojiToAscii(text, getApplicationContext());
}
return text;
}
private void handleAction(Intent intent, String action, Prefs prefs) {
switch (action) {
case ACTION_REQUEST_DEVICEINFO:
mGBDevice.sendDeviceUpdateIntent(this);
break;
case ACTION_NOTIFICATION: {
int desiredId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1);
NotificationSpec notificationSpec = new NotificationSpec(desiredId);
notificationSpec.phoneNumber = intent.getStringExtra(EXTRA_NOTIFICATION_PHONENUMBER);
notificationSpec.sender = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_SENDER));
notificationSpec.subject = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_SUBJECT));
notificationSpec.title = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_TITLE));
notificationSpec.body = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_BODY));
notificationSpec.sourceName = intent.getStringExtra(EXTRA_NOTIFICATION_SOURCENAME);
notificationSpec.type = (NotificationType) intent.getSerializableExtra(EXTRA_NOTIFICATION_TYPE);
notificationSpec.attachedActions = (ArrayList<NotificationSpec.Action>) intent.getSerializableExtra(EXTRA_NOTIFICATION_ACTIONS);
notificationSpec.pebbleColor = (byte) intent.getSerializableExtra(EXTRA_NOTIFICATION_PEBBLE_COLOR);
notificationSpec.flags = intent.getIntExtra(EXTRA_NOTIFICATION_FLAGS, 0);
notificationSpec.sourceAppId = intent.getStringExtra(EXTRA_NOTIFICATION_SOURCEAPPID);
if (notificationSpec.type == NotificationType.GENERIC_SMS && notificationSpec.phoneNumber != null) {
GBApplication.getIDSenderLookup().add(notificationSpec.getId(), notificationSpec.phoneNumber);
}
//TODO: check if at least one of the attached actions is a reply action instead?
if ((notificationSpec.attachedActions != null && notificationSpec.attachedActions.size() > 0)
|| (notificationSpec.type == NotificationType.GENERIC_SMS && notificationSpec.phoneNumber != null)) {
// NOTE: maybe not where it belongs
// I would rather like to save that as an array in SharedPreferences
// this would work but I dont know how to do the same in the Settings Activity's xml
ArrayList<String> replies = new ArrayList<>();
for (int i = 1; i <= 16; i++) {
String reply = prefs.getString("canned_reply_" + i, null);
if (reply != null && !reply.equals("")) {
replies.add(reply);
}
}
notificationSpec.cannedReplies = replies.toArray(new String[replies.size()]);
}
mDeviceSupport.onNotification(notificationSpec);
break;
}
case ACTION_DELETE_NOTIFICATION: {
mDeviceSupport.onDeleteNotification(intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1));
break;
}
case ACTION_ADD_CALENDAREVENT: {
CalendarEventSpec calendarEventSpec = new CalendarEventSpec();
calendarEventSpec.id = intent.getLongExtra(EXTRA_CALENDAREVENT_ID, -1);
calendarEventSpec.type = intent.getByteExtra(EXTRA_CALENDAREVENT_TYPE, (byte) -1);
calendarEventSpec.timestamp = intent.getIntExtra(EXTRA_CALENDAREVENT_TIMESTAMP, -1);
calendarEventSpec.durationInSeconds = intent.getIntExtra(EXTRA_CALENDAREVENT_DURATION, -1);
calendarEventSpec.title = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_TITLE));
calendarEventSpec.description = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_DESCRIPTION));
calendarEventSpec.location = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_LOCATION));
mDeviceSupport.onAddCalendarEvent(calendarEventSpec);
break;
}
case ACTION_DELETE_CALENDAREVENT: {
long id = intent.getLongExtra(EXTRA_CALENDAREVENT_ID, -1);
byte type = intent.getByteExtra(EXTRA_CALENDAREVENT_TYPE, (byte) -1);
mDeviceSupport.onDeleteCalendarEvent(type, id);
break;
}
case ACTION_RESET: {
int flags = intent.getIntExtra(EXTRA_RESET_FLAGS, 0);
mDeviceSupport.onReset(flags);
break;
}
case ACTION_HEARTRATE_TEST: {
mDeviceSupport.onHeartRateTest();
break;
}
case ACTION_FETCH_RECORDED_DATA: {
int dataTypes = intent.getIntExtra(EXTRA_RECORDED_DATA_TYPES, 0);
mDeviceSupport.onFetchRecordedData(dataTypes);
break;
}
case ACTION_DISCONNECT: {
mDeviceSupport.dispose();
if (mGBDevice != null) {
mGBDevice.setState(GBDevice.State.NOT_CONNECTED);
mGBDevice.sendDeviceUpdateIntent(this);
}
setReceiversEnableState(false, false, null);
mGBDevice = null;
mDeviceSupport = null;
mCoordinator = null;
break;
}
case ACTION_FIND_DEVICE: {
boolean start = intent.getBooleanExtra(EXTRA_FIND_START, false);
mDeviceSupport.onFindDevice(start);
break;
}
case ACTION_SET_CONSTANT_VIBRATION: {
int intensity = intent.getIntExtra(EXTRA_VIBRATION_INTENSITY, 0);
mDeviceSupport.onSetConstantVibration(intensity);
break;
}
case ACTION_CALLSTATE:
CallSpec callSpec = new CallSpec();
callSpec.command = intent.getIntExtra(EXTRA_CALL_COMMAND, CallSpec.CALL_UNDEFINED);
callSpec.number = intent.getStringExtra(EXTRA_CALL_PHONENUMBER);
callSpec.name = sanitizeNotifText(intent.getStringExtra(EXTRA_CALL_DISPLAYNAME));
mDeviceSupport.onSetCallState(callSpec);
break;
case ACTION_SETCANNEDMESSAGES:
int type = intent.getIntExtra(EXTRA_CANNEDMESSAGES_TYPE, -1);
String[] cannedMessages = intent.getStringArrayExtra(EXTRA_CANNEDMESSAGES);
CannedMessagesSpec cannedMessagesSpec = new CannedMessagesSpec();
cannedMessagesSpec.type = type;
cannedMessagesSpec.cannedMessages = cannedMessages;
mDeviceSupport.onSetCannedMessages(cannedMessagesSpec);
break;
case ACTION_SETTIME:
mDeviceSupport.onSetTime();
break;
case ACTION_SETMUSICINFO:
MusicSpec musicSpec = new MusicSpec();
musicSpec.artist = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_ARTIST));
musicSpec.album = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_ALBUM));
musicSpec.track = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_TRACK));
musicSpec.duration = intent.getIntExtra(EXTRA_MUSIC_DURATION, 0);
musicSpec.trackCount = intent.getIntExtra(EXTRA_MUSIC_TRACKCOUNT, 0);
musicSpec.trackNr = intent.getIntExtra(EXTRA_MUSIC_TRACKNR, 0);
mDeviceSupport.onSetMusicInfo(musicSpec);
break;
case ACTION_SETMUSICSTATE:
MusicStateSpec stateSpec = new MusicStateSpec();
stateSpec.shuffle = intent.getByteExtra(EXTRA_MUSIC_SHUFFLE, (byte) 0);
stateSpec.repeat = intent.getByteExtra(EXTRA_MUSIC_REPEAT, (byte) 0);
stateSpec.position = intent.getIntExtra(EXTRA_MUSIC_POSITION, 0);
stateSpec.playRate = intent.getIntExtra(EXTRA_MUSIC_RATE, 0);
stateSpec.state = intent.getByteExtra(EXTRA_MUSIC_STATE, (byte) 0);
mDeviceSupport.onSetMusicState(stateSpec);
break;
case ACTION_REQUEST_APPINFO:
mDeviceSupport.onAppInfoReq();
break;
case ACTION_REQUEST_SCREENSHOT:
mDeviceSupport.onScreenshotReq();
break;
case ACTION_STARTAPP: {
UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
boolean start = intent.getBooleanExtra(EXTRA_APP_START, true);
mDeviceSupport.onAppStart(uuid, start);
break;
}
case ACTION_DELETEAPP: {
UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
mDeviceSupport.onAppDelete(uuid);
break;
}
case ACTION_APP_CONFIGURE: {
UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
String config = intent.getStringExtra(EXTRA_APP_CONFIG);
Integer id = null;
if (intent.hasExtra(EXTRA_APP_CONFIG_ID)) {
id = intent.getIntExtra(EXTRA_APP_CONFIG_ID, 0);
}
mDeviceSupport.onAppConfiguration(uuid, config, id);
break;
}
case ACTION_APP_REORDER: {
UUID[] uuids = (UUID[]) intent.getSerializableExtra(EXTRA_APP_UUID);
mDeviceSupport.onAppReorder(uuids);
break;
}
case ACTION_INSTALL:
Uri uri = intent.getParcelableExtra(EXTRA_URI);
if (uri != null) {
LOG.info("will try to install app/fw");
mDeviceSupport.onInstallApp(uri);
}
break;
case ACTION_SET_ALARMS:
ArrayList<? extends Alarm> alarms = (ArrayList<? extends Alarm>) intent.getSerializableExtra(EXTRA_ALARMS);
mDeviceSupport.onSetAlarms(alarms);
break;
case ACTION_ENABLE_REALTIME_STEPS: {
boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
mDeviceSupport.onEnableRealtimeSteps(enable);
break;
}
case ACTION_ENABLE_HEARTRATE_SLEEP_SUPPORT: {
boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
mDeviceSupport.onEnableHeartRateSleepSupport(enable);
break;
}
case ACTION_SET_HEARTRATE_MEASUREMENT_INTERVAL: {
int seconds = intent.getIntExtra(EXTRA_INTERVAL_SECONDS, 0);
mDeviceSupport.onSetHeartRateMeasurementInterval(seconds);
break;
}
case ACTION_ENABLE_REALTIME_HEARTRATE_MEASUREMENT: {
boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
mDeviceSupport.onEnableRealtimeHeartRateMeasurement(enable);
break;
}
case ACTION_SEND_CONFIGURATION: {
String config = intent.getStringExtra(EXTRA_CONFIG);
mDeviceSupport.onSendConfiguration(config);
break;
}
case ACTION_READ_CONFIGURATION: {
String config = intent.getStringExtra(EXTRA_CONFIG);
mDeviceSupport.onReadConfiguration(config);
break;
}
case ACTION_TEST_NEW_FUNCTION: {
mDeviceSupport.onTestNewFunction();
break;
}
case ACTION_SEND_WEATHER: {
WeatherSpec weatherSpec = intent.getParcelableExtra(EXTRA_WEATHER);
if (weatherSpec != null) {
mDeviceSupport.onSendWeather(weatherSpec);
}
break;
}
case ACTION_SET_LED_COLOR:
int color = intent.getIntExtra(EXTRA_LED_COLOR, 0);
if (color != 0) {
mDeviceSupport.onSetLedColor(color);
}
break;
case ACTION_SET_FM_FREQUENCY:
float frequency = intent.getFloatExtra(EXTRA_FM_FREQUENCY, -1);
if (frequency != -1) {
mDeviceSupport.onSetFmFrequency(frequency);
}
break;
}
}
/**
* Disposes the current DeviceSupport instance (if any) and sets a new device support instance
* (if not null).
*
* @param deviceSupport
*/
private void setDeviceSupport(@Nullable DeviceSupport deviceSupport) {
if (deviceSupport != mDeviceSupport && mDeviceSupport != null) {
mDeviceSupport.dispose();
mDeviceSupport = null;
mGBDevice = null;
mCoordinator = null;
}
mDeviceSupport = deviceSupport;
mGBDevice = mDeviceSupport != null ? mDeviceSupport.getDevice() : null;
mCoordinator = mGBDevice != null ? DeviceHelper.getInstance().getCoordinator(mGBDevice) : null;
}
private void start() {
if (!mStarted) {
startForeground(GB.NOTIFICATION_ID, GB.createNotification(getString(R.string.gadgetbridge_running), this));
mStarted = true;
}
}
public boolean isStarted() {
return mStarted;
}
private boolean isConnected() {
return mGBDevice != null && mGBDevice.isConnected();
}
private boolean isConnecting() {
return mGBDevice != null && mGBDevice.isConnecting();
}
private boolean isInitialized() {
return mGBDevice != null && mGBDevice.isInitialized();
}
private void setReceiversEnableState(boolean enable, boolean initialized, DeviceCoordinator coordinator) {
LOG.info("Setting broadcast receivers to: " + enable);
if (enable && initialized && coordinator != null && coordinator.supportsCalendarEvents()) {
if (mCalendarReceiver == null && getPrefs().getBoolean("enable_calendar_sync", true)) {
if (!(GBApplication.isRunningMarshmallowOrLater() && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_DENIED)) {
IntentFilter calendarIntentFilter = new IntentFilter();
calendarIntentFilter.addAction("android.intent.action.PROVIDER_CHANGED");
calendarIntentFilter.addDataScheme("content");
calendarIntentFilter.addDataAuthority("com.android.calendar", null);
mCalendarReceiver = new CalendarReceiver(mGBDevice);
registerReceiver(mCalendarReceiver, calendarIntentFilter);
}
}
if (mAlarmReceiver == null) {
mAlarmReceiver = new AlarmReceiver();
registerReceiver(mAlarmReceiver, new IntentFilter("DAILY_ALARM"));
}
} else {
if (mCalendarReceiver != null) {
unregisterReceiver(mCalendarReceiver);
mCalendarReceiver = null;
}
if (mAlarmReceiver != null) {
unregisterReceiver(mAlarmReceiver);
mAlarmReceiver = null;
}
}
if (enable) {
if (mPhoneCallReceiver == null) {
mPhoneCallReceiver = new PhoneCallReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
filter.addAction("nodomain.freeyourgadget.gadgetbridge.MUTE_CALL");
registerReceiver(mPhoneCallReceiver, filter);
}
if (mSMSReceiver == null) {
mSMSReceiver = new SMSReceiver();
registerReceiver(mSMSReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
if (mPebbleReceiver == null) {
mPebbleReceiver = new PebbleReceiver();
registerReceiver(mPebbleReceiver, new IntentFilter("com.getpebble.action.SEND_NOTIFICATION"));
}
if (mMusicPlaybackReceiver == null && coordinator != null && coordinator.supportsMusicInfo()) {
mMusicPlaybackReceiver = new MusicPlaybackReceiver();
IntentFilter filter = new IntentFilter();
for (String action : mMusicActions) {
filter.addAction(action);
}
registerReceiver(mMusicPlaybackReceiver, filter);
}
if (mTimeChangeReceiver == null) {
mTimeChangeReceiver = new TimeChangeReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.TIME_SET");
filter.addAction("android.intent.action.TIMEZONE_CHANGED");
registerReceiver(mTimeChangeReceiver, filter);
}
if (mBlueToothConnectReceiver == null) {
mBlueToothConnectReceiver = new BluetoothConnectReceiver(this);
registerReceiver(mBlueToothConnectReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
}
if (mBlueToothPairingRequestReceiver == null) {
mBlueToothPairingRequestReceiver = new BluetoothPairingRequestReceiver(this);
registerReceiver(mBlueToothPairingRequestReceiver, new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST));
}
if (mAlarmClockReceiver == null) {
mAlarmClockReceiver = new AlarmClockReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(AlarmClockReceiver.ALARM_ALERT_ACTION);
filter.addAction(AlarmClockReceiver.ALARM_DONE_ACTION);
filter.addAction(AlarmClockReceiver.GOOGLE_CLOCK_ALARM_ALERT_ACTION);
filter.addAction(AlarmClockReceiver.GOOGLE_CLOCK_ALARM_DONE_ACTION);
registerReceiver(mAlarmClockReceiver, filter);
}
if (mCMWeatherReceiver == null && coordinator != null && coordinator.supportsWeather()) {
mCMWeatherReceiver = new CMWeatherReceiver();
registerReceiver(mCMWeatherReceiver, new IntentFilter("GB_UPDATE_WEATHER"));
}
if (GBApplication.isRunningOreoOrLater()) {
if (mLineageOsWeatherReceiver == null && coordinator != null && coordinator.supportsWeather()) {
mLineageOsWeatherReceiver = new LineageOsWeatherReceiver();
registerReceiver(mLineageOsWeatherReceiver, new IntentFilter("GB_UPDATE_WEATHER"));
}
}
if (mOmniJawsObserver == null && coordinator != null && coordinator.supportsWeather()) {
try {
mOmniJawsObserver = new OmniJawsObserver(new Handler());
getContentResolver().registerContentObserver(OmniJawsObserver.WEATHER_URI, true, mOmniJawsObserver);
} catch (PackageManager.NameNotFoundException e) {
//Nothing wrong, it just means we're not running on omnirom.
}
}
if (GBApplication.getPrefs().getBoolean("auto_fetch_enabled", false) &&
coordinator != null && coordinator.supportsActivityDataFetching() && mGBAutoFetchReceiver == null) {
mGBAutoFetchReceiver = new GBAutoFetchReceiver();
registerReceiver(mGBAutoFetchReceiver, new IntentFilter("android.intent.action.USER_PRESENT"));
}
if (mAutoConnectInvervalReceiver == null) {
mAutoConnectInvervalReceiver= new AutoConnectIntervalReceiver(this);
registerReceiver(mAutoConnectInvervalReceiver, new IntentFilter("GB_RECONNECT"));
}
} else {
if (mPhoneCallReceiver != null) {
unregisterReceiver(mPhoneCallReceiver);
mPhoneCallReceiver = null;
}
if (mSMSReceiver != null) {
unregisterReceiver(mSMSReceiver);
mSMSReceiver = null;
}
if (mPebbleReceiver != null) {
unregisterReceiver(mPebbleReceiver);
mPebbleReceiver = null;
}
if (mMusicPlaybackReceiver != null) {
unregisterReceiver(mMusicPlaybackReceiver);
mMusicPlaybackReceiver = null;
}
if (mTimeChangeReceiver != null) {
unregisterReceiver(mTimeChangeReceiver);
mTimeChangeReceiver = null;
}
if (mBlueToothConnectReceiver != null) {
unregisterReceiver(mBlueToothConnectReceiver);
mBlueToothConnectReceiver = null;
}
if (mBlueToothPairingRequestReceiver != null) {
unregisterReceiver(mBlueToothPairingRequestReceiver);
mBlueToothPairingRequestReceiver = null;
}
if (mAlarmClockReceiver != null) {
unregisterReceiver(mAlarmClockReceiver);
mAlarmClockReceiver = null;
}
if (mCMWeatherReceiver != null) {
unregisterReceiver(mCMWeatherReceiver);
mCMWeatherReceiver = null;
}
if (mLineageOsWeatherReceiver != null) {
unregisterReceiver(mLineageOsWeatherReceiver);
mLineageOsWeatherReceiver = null;
}
if (mOmniJawsObserver != null) {
getContentResolver().unregisterContentObserver(mOmniJawsObserver);
}
if (mGBAutoFetchReceiver != null) {
unregisterReceiver(mGBAutoFetchReceiver);
mGBAutoFetchReceiver = null;
}
if (mAutoConnectInvervalReceiver != null) {
unregisterReceiver(mAutoConnectInvervalReceiver);
mAutoConnectInvervalReceiver = null;
}
}
}
@Override
public void onDestroy() {
if (hasPrefs()) {
getPrefs().getPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
LOG.debug("DeviceCommunicationService is being destroyed");
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
setReceiversEnableState(false, false, null); // disable BroadcastReceivers
setDeviceSupport(null);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (nm != null) {
nm.cancel(GB.NOTIFICATION_ID); // need to do this because the updated notification won't be cancelled when service stops
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (GBPrefs.AUTO_RECONNECT.equals(key)) {
boolean autoReconnect = getGBPrefs().getAutoReconnect();
if (mDeviceSupport != null) {
mDeviceSupport.setAutoReconnect(autoReconnect);
}
}
if (GBPrefs.CHART_MAX_HEART_RATE.equals(key) || GBPrefs.CHART_MIN_HEART_RATE.equals(key)) {
HeartRateUtils.getInstance().updateCachedHeartRatePreferences();
}
}
protected boolean hasPrefs() {
return getPrefs().getPreferences() != null;
}
public Prefs getPrefs() {
return GBApplication.getPrefs();
}
public GBPrefs getGBPrefs() {
return GBApplication.getGBPrefs();
}
public GBDevice getGBDevice() {
return mGBDevice;
}
}
| app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/DeviceCommunicationService.java | /* Copyright (C) 2015-2019 Andreas Böhler, Andreas Shimokawa, Avamander,
Carsten Pfeiffer, Daniel Dakhno, Daniele Gobbetti, Daniel Hauck, Dikay900,
Frank Slezak, ivanovlev, João Paulo Barraca, José Rebelo, Julien Pivotto,
Kasha, keeshii, Martin, Matthieu Baerts, Nephiel, Sebastian Kranz, Sergey
Trofimov, Steffen Liebergeld, Taavi Eomäe, Uwe Hermann
This file is part of Gadgetbridge.
Gadgetbridge is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Gadgetbridge is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package nodomain.freeyourgadget.gadgetbridge.service;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.activities.HeartRateUtils;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceCoordinator;
import nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmClockReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.BluetoothConnectReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.BluetoothPairingRequestReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.CMWeatherReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.CalendarReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.LineageOsWeatherReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.MusicPlaybackReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.OmniJawsObserver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.PebbleReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.PhoneCallReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.SMSReceiver;
import nodomain.freeyourgadget.gadgetbridge.externalevents.TimeChangeReceiver;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationType;
import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec;
import nodomain.freeyourgadget.gadgetbridge.service.receivers.AutoConnectIntervalReceiver;
import nodomain.freeyourgadget.gadgetbridge.service.receivers.GBAutoFetchReceiver;
import nodomain.freeyourgadget.gadgetbridge.util.DeviceHelper;
import nodomain.freeyourgadget.gadgetbridge.util.EmojiConverter;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
import nodomain.freeyourgadget.gadgetbridge.util.GBPrefs;
import nodomain.freeyourgadget.gadgetbridge.util.Prefs;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_ADD_CALENDAREVENT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_APP_CONFIGURE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_APP_REORDER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_CALLSTATE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_CONNECT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_DELETEAPP;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_DELETE_CALENDAREVENT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_DELETE_NOTIFICATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_DISCONNECT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_ENABLE_HEARTRATE_SLEEP_SUPPORT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_ENABLE_REALTIME_HEARTRATE_MEASUREMENT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_ENABLE_REALTIME_STEPS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_FETCH_RECORDED_DATA;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_FIND_DEVICE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_HEARTRATE_TEST;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_INSTALL;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_NOTIFICATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_READ_CONFIGURATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_REQUEST_APPINFO;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_REQUEST_DEVICEINFO;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_REQUEST_SCREENSHOT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_RESET;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SEND_CONFIGURATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SEND_WEATHER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SETCANNEDMESSAGES;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SETMUSICINFO;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SETMUSICSTATE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SETTIME;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_ALARMS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_CONSTANT_VIBRATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_FM_FREQUENCY;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_HEARTRATE_MEASUREMENT_INTERVAL;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_SET_LED_COLOR;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_START;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_STARTAPP;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.ACTION_TEST_NEW_FUNCTION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_ALARMS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_CONFIG;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_CONFIG_ID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_START;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_UUID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_BOOLEAN_ENABLE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_DESCRIPTION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_ID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_LOCATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_TIMESTAMP;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_TITLE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALENDAREVENT_TYPE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALL_COMMAND;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALL_DISPLAYNAME;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CALL_PHONENUMBER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CANNEDMESSAGES;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CANNEDMESSAGES_TYPE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CONFIG;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_CONNECT_FIRST_TIME;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_FIND_START;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_FM_FREQUENCY;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_INTERVAL_SECONDS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_LED_COLOR;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_ALBUM;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_ARTIST;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_POSITION;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_RATE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_REPEAT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_SHUFFLE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_STATE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_TRACK;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_TRACKCOUNT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_MUSIC_TRACKNR;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_ACTIONS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_BODY;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_FLAGS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_ID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_PEBBLE_COLOR;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_PHONENUMBER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_SENDER;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_SOURCEAPPID;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_SOURCENAME;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_SUBJECT;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_TITLE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_NOTIFICATION_TYPE;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_RECORDED_DATA_TYPES;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_RESET_FLAGS;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_URI;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_VIBRATION_INTENSITY;
import static nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_WEATHER;
public class DeviceCommunicationService extends Service implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(DeviceCommunicationService.class);
@SuppressLint("StaticFieldLeak") // only used for test cases
private static DeviceSupportFactory DEVICE_SUPPORT_FACTORY = null;
private boolean mStarted = false;
private DeviceSupportFactory mFactory;
private GBDevice mGBDevice = null;
private DeviceSupport mDeviceSupport;
private DeviceCoordinator mCoordinator = null;
private PhoneCallReceiver mPhoneCallReceiver = null;
private SMSReceiver mSMSReceiver = null;
private PebbleReceiver mPebbleReceiver = null;
private MusicPlaybackReceiver mMusicPlaybackReceiver = null;
private TimeChangeReceiver mTimeChangeReceiver = null;
private BluetoothConnectReceiver mBlueToothConnectReceiver = null;
private BluetoothPairingRequestReceiver mBlueToothPairingRequestReceiver = null;
private AlarmClockReceiver mAlarmClockReceiver = null;
private GBAutoFetchReceiver mGBAutoFetchReceiver = null;
private AutoConnectIntervalReceiver mAutoConnectInvervalReceiver= null;
private AlarmReceiver mAlarmReceiver = null;
private CalendarReceiver mCalendarReceiver = null;
private CMWeatherReceiver mCMWeatherReceiver = null;
private LineageOsWeatherReceiver mLineageOsWeatherReceiver = null;
private OmniJawsObserver mOmniJawsObserver = null;
private final String[] mMusicActions = {
"com.android.music.metachanged",
"com.android.music.playstatechanged",
"com.android.music.queuechanged",
"com.android.music.playbackcomplete",
"net.sourceforge.subsonic.androidapp.EVENT_META_CHANGED",
"com.maxmpz.audioplayer.TPOS_SYNC",
"com.maxmpz.audioplayer.STATUS_CHANGED",
"com.maxmpz.audioplayer.PLAYING_MODE_CHANGED",
"com.spotify.music.metadatachanged",
"com.spotify.music.playbackstatechanged"
};
/**
* For testing!
*
* @param factory
*/
public static void setDeviceSupportFactory(DeviceSupportFactory factory) {
DEVICE_SUPPORT_FACTORY = factory;
}
public DeviceCommunicationService() {
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (GBDevice.ACTION_DEVICE_CHANGED.equals(action)) {
GBDevice device = intent.getParcelableExtra(GBDevice.EXTRA_DEVICE);
if (mGBDevice != null && mGBDevice.equals(device)) {
mGBDevice = device;
mCoordinator = DeviceHelper.getInstance().getCoordinator(device);
boolean enableReceivers = mDeviceSupport != null && (mDeviceSupport.useAutoConnect() || mGBDevice.isInitialized());
setReceiversEnableState(enableReceivers, mGBDevice.isInitialized(), mCoordinator);
} else {
LOG.error("Got ACTION_DEVICE_CHANGED from unexpected device: " + device);
}
}
}
};
@Override
public void onCreate() {
LOG.debug("DeviceCommunicationService is being created");
super.onCreate();
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(GBDevice.ACTION_DEVICE_CHANGED));
mFactory = getDeviceSupportFactory();
if (hasPrefs()) {
getPrefs().getPreferences().registerOnSharedPreferenceChangeListener(this);
}
}
private DeviceSupportFactory getDeviceSupportFactory() {
if (DEVICE_SUPPORT_FACTORY != null) {
return DEVICE_SUPPORT_FACTORY;
}
return new DeviceSupportFactory(this);
}
@Override
public synchronized int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
LOG.info("no intent");
return START_NOT_STICKY;
}
String action = intent.getAction();
boolean firstTime = intent.getBooleanExtra(EXTRA_CONNECT_FIRST_TIME, false);
if (action == null) {
LOG.info("no action");
return START_NOT_STICKY;
}
LOG.debug("Service startcommand: " + action);
if (!action.equals(ACTION_START) && !action.equals(ACTION_CONNECT)) {
if (!mStarted) {
// using the service before issuing ACTION_START
LOG.info("Must start service with " + ACTION_START + " or " + ACTION_CONNECT + " before using it: " + action);
return START_NOT_STICKY;
}
if (mDeviceSupport == null || (!isInitialized() && !mDeviceSupport.useAutoConnect())) {
// trying to send notification without valid Bluetooth connection
if (mGBDevice != null) {
// at least send back the current device state
mGBDevice.sendDeviceUpdateIntent(this);
}
return START_STICKY;
}
}
// when we get past this, we should have valid mDeviceSupport and mGBDevice instances
Prefs prefs = getPrefs();
switch (action) {
case ACTION_START:
start();
break;
case ACTION_CONNECT:
start(); // ensure started
GBDevice gbDevice = intent.getParcelableExtra(GBDevice.EXTRA_DEVICE);
String btDeviceAddress = null;
if (gbDevice == null) {
if (prefs != null) { // may be null in test cases
btDeviceAddress = prefs.getString("last_device_address", null);
if (btDeviceAddress != null) {
gbDevice = DeviceHelper.getInstance().findAvailableDevice(btDeviceAddress, this);
}
}
} else {
btDeviceAddress = gbDevice.getAddress();
}
boolean autoReconnect = GBPrefs.AUTO_RECONNECT_DEFAULT;
if (prefs != null && prefs.getPreferences() != null) {
prefs.getPreferences().edit().putString("last_device_address", btDeviceAddress).apply();
autoReconnect = getGBPrefs().getAutoReconnect();
}
if (gbDevice != null && !isConnecting() && !isConnected()) {
setDeviceSupport(null);
try {
DeviceSupport deviceSupport = mFactory.createDeviceSupport(gbDevice);
if (deviceSupport != null) {
setDeviceSupport(deviceSupport);
if (firstTime) {
deviceSupport.connectFirstTime();
} else {
deviceSupport.setAutoReconnect(autoReconnect);
deviceSupport.connect();
}
} else {
GB.toast(this, getString(R.string.cannot_connect, "Can't create device support"), Toast.LENGTH_SHORT, GB.ERROR);
}
} catch (Exception e) {
GB.toast(this, getString(R.string.cannot_connect, e.getMessage()), Toast.LENGTH_SHORT, GB.ERROR, e);
setDeviceSupport(null);
}
} else if (mGBDevice != null) {
// send an update at least
mGBDevice.sendDeviceUpdateIntent(this);
}
break;
default:
if (mDeviceSupport == null || mGBDevice == null) {
LOG.warn("device support:" + mDeviceSupport + ", device: " + mGBDevice + ", aborting");
} else {
handleAction(intent, action, prefs);
}
break;
}
return START_STICKY;
}
/**
* @param text original text
* @return 'text' or a new String without non supported chars like emoticons, etc.
*/
private String sanitizeNotifText(String text) {
if (text == null || text.length() == 0)
return text;
text = mDeviceSupport.customStringFilter(text);
if (!mCoordinator.supportsUnicodeEmojis()) {
return EmojiConverter.convertUnicodeEmojiToAscii(text, getApplicationContext());
}
return text;
}
private void handleAction(Intent intent, String action, Prefs prefs) {
switch (action) {
case ACTION_REQUEST_DEVICEINFO:
mGBDevice.sendDeviceUpdateIntent(this);
break;
case ACTION_NOTIFICATION: {
int desiredId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1);
NotificationSpec notificationSpec = new NotificationSpec(desiredId);
notificationSpec.phoneNumber = intent.getStringExtra(EXTRA_NOTIFICATION_PHONENUMBER);
notificationSpec.sender = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_SENDER));
notificationSpec.subject = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_SUBJECT));
notificationSpec.title = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_TITLE));
notificationSpec.body = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_BODY));
notificationSpec.sourceName = intent.getStringExtra(EXTRA_NOTIFICATION_SOURCENAME);
notificationSpec.type = (NotificationType) intent.getSerializableExtra(EXTRA_NOTIFICATION_TYPE);
notificationSpec.attachedActions = (ArrayList<NotificationSpec.Action>) intent.getSerializableExtra(EXTRA_NOTIFICATION_ACTIONS);
notificationSpec.pebbleColor = (byte) intent.getSerializableExtra(EXTRA_NOTIFICATION_PEBBLE_COLOR);
notificationSpec.flags = intent.getIntExtra(EXTRA_NOTIFICATION_FLAGS, 0);
notificationSpec.sourceAppId = intent.getStringExtra(EXTRA_NOTIFICATION_SOURCEAPPID);
if (notificationSpec.type == NotificationType.GENERIC_SMS && notificationSpec.phoneNumber != null) {
GBApplication.getIDSenderLookup().add(notificationSpec.getId(), notificationSpec.phoneNumber);
}
//TODO: check if at least one of the attached actions is a reply action instead?
if ((notificationSpec.attachedActions != null && notificationSpec.attachedActions.size() > 0)
|| (notificationSpec.type == NotificationType.GENERIC_SMS && notificationSpec.phoneNumber != null)) {
// NOTE: maybe not where it belongs
// I would rather like to save that as an array in SharedPreferences
// this would work but I dont know how to do the same in the Settings Activity's xml
ArrayList<String> replies = new ArrayList<>();
for (int i = 1; i <= 16; i++) {
String reply = prefs.getString("canned_reply_" + i, null);
if (reply != null && !reply.equals("")) {
replies.add(reply);
}
}
notificationSpec.cannedReplies = replies.toArray(new String[replies.size()]);
}
mDeviceSupport.onNotification(notificationSpec);
break;
}
case ACTION_DELETE_NOTIFICATION: {
mDeviceSupport.onDeleteNotification(intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1));
break;
}
case ACTION_ADD_CALENDAREVENT: {
CalendarEventSpec calendarEventSpec = new CalendarEventSpec();
calendarEventSpec.id = intent.getLongExtra(EXTRA_CALENDAREVENT_ID, -1);
calendarEventSpec.type = intent.getByteExtra(EXTRA_CALENDAREVENT_TYPE, (byte) -1);
calendarEventSpec.timestamp = intent.getIntExtra(EXTRA_CALENDAREVENT_TIMESTAMP, -1);
calendarEventSpec.durationInSeconds = intent.getIntExtra(EXTRA_CALENDAREVENT_DURATION, -1);
calendarEventSpec.title = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_TITLE));
calendarEventSpec.description = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_DESCRIPTION));
calendarEventSpec.location = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_LOCATION));
mDeviceSupport.onAddCalendarEvent(calendarEventSpec);
break;
}
case ACTION_DELETE_CALENDAREVENT: {
long id = intent.getLongExtra(EXTRA_CALENDAREVENT_ID, -1);
byte type = intent.getByteExtra(EXTRA_CALENDAREVENT_TYPE, (byte) -1);
mDeviceSupport.onDeleteCalendarEvent(type, id);
break;
}
case ACTION_RESET: {
int flags = intent.getIntExtra(EXTRA_RESET_FLAGS, 0);
mDeviceSupport.onReset(flags);
break;
}
case ACTION_HEARTRATE_TEST: {
mDeviceSupport.onHeartRateTest();
break;
}
case ACTION_FETCH_RECORDED_DATA: {
int dataTypes = intent.getIntExtra(EXTRA_RECORDED_DATA_TYPES, 0);
mDeviceSupport.onFetchRecordedData(dataTypes);
break;
}
case ACTION_DISCONNECT: {
mDeviceSupport.dispose();
if (mGBDevice != null) {
mGBDevice.setState(GBDevice.State.NOT_CONNECTED);
mGBDevice.sendDeviceUpdateIntent(this);
}
setReceiversEnableState(false, false, null);
mGBDevice = null;
mDeviceSupport = null;
mCoordinator = null;
break;
}
case ACTION_FIND_DEVICE: {
boolean start = intent.getBooleanExtra(EXTRA_FIND_START, false);
mDeviceSupport.onFindDevice(start);
break;
}
case ACTION_SET_CONSTANT_VIBRATION: {
int intensity = intent.getIntExtra(EXTRA_VIBRATION_INTENSITY, 0);
mDeviceSupport.onSetConstantVibration(intensity);
break;
}
case ACTION_CALLSTATE:
CallSpec callSpec = new CallSpec();
callSpec.command = intent.getIntExtra(EXTRA_CALL_COMMAND, CallSpec.CALL_UNDEFINED);
callSpec.number = intent.getStringExtra(EXTRA_CALL_PHONENUMBER);
callSpec.name = sanitizeNotifText(intent.getStringExtra(EXTRA_CALL_DISPLAYNAME));
mDeviceSupport.onSetCallState(callSpec);
break;
case ACTION_SETCANNEDMESSAGES:
int type = intent.getIntExtra(EXTRA_CANNEDMESSAGES_TYPE, -1);
String[] cannedMessages = intent.getStringArrayExtra(EXTRA_CANNEDMESSAGES);
CannedMessagesSpec cannedMessagesSpec = new CannedMessagesSpec();
cannedMessagesSpec.type = type;
cannedMessagesSpec.cannedMessages = cannedMessages;
mDeviceSupport.onSetCannedMessages(cannedMessagesSpec);
break;
case ACTION_SETTIME:
mDeviceSupport.onSetTime();
break;
case ACTION_SETMUSICINFO:
MusicSpec musicSpec = new MusicSpec();
musicSpec.artist = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_ARTIST));
musicSpec.album = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_ALBUM));
musicSpec.track = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_TRACK));
musicSpec.duration = intent.getIntExtra(EXTRA_MUSIC_DURATION, 0);
musicSpec.trackCount = intent.getIntExtra(EXTRA_MUSIC_TRACKCOUNT, 0);
musicSpec.trackNr = intent.getIntExtra(EXTRA_MUSIC_TRACKNR, 0);
mDeviceSupport.onSetMusicInfo(musicSpec);
break;
case ACTION_SETMUSICSTATE:
MusicStateSpec stateSpec = new MusicStateSpec();
stateSpec.shuffle = intent.getByteExtra(EXTRA_MUSIC_SHUFFLE, (byte) 0);
stateSpec.repeat = intent.getByteExtra(EXTRA_MUSIC_REPEAT, (byte) 0);
stateSpec.position = intent.getIntExtra(EXTRA_MUSIC_POSITION, 0);
stateSpec.playRate = intent.getIntExtra(EXTRA_MUSIC_RATE, 0);
stateSpec.state = intent.getByteExtra(EXTRA_MUSIC_STATE, (byte) 0);
mDeviceSupport.onSetMusicState(stateSpec);
break;
case ACTION_REQUEST_APPINFO:
mDeviceSupport.onAppInfoReq();
break;
case ACTION_REQUEST_SCREENSHOT:
mDeviceSupport.onScreenshotReq();
break;
case ACTION_STARTAPP: {
UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
boolean start = intent.getBooleanExtra(EXTRA_APP_START, true);
mDeviceSupport.onAppStart(uuid, start);
break;
}
case ACTION_DELETEAPP: {
UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
mDeviceSupport.onAppDelete(uuid);
break;
}
case ACTION_APP_CONFIGURE: {
UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
String config = intent.getStringExtra(EXTRA_APP_CONFIG);
Integer id = null;
if (intent.hasExtra(EXTRA_APP_CONFIG_ID)) {
id = intent.getIntExtra(EXTRA_APP_CONFIG_ID, 0);
}
mDeviceSupport.onAppConfiguration(uuid, config, id);
break;
}
case ACTION_APP_REORDER: {
UUID[] uuids = (UUID[]) intent.getSerializableExtra(EXTRA_APP_UUID);
mDeviceSupport.onAppReorder(uuids);
break;
}
case ACTION_INSTALL:
Uri uri = intent.getParcelableExtra(EXTRA_URI);
if (uri != null) {
LOG.info("will try to install app/fw");
mDeviceSupport.onInstallApp(uri);
}
break;
case ACTION_SET_ALARMS:
ArrayList<? extends Alarm> alarms = (ArrayList<? extends Alarm>) intent.getSerializableExtra(EXTRA_ALARMS);
mDeviceSupport.onSetAlarms(alarms);
break;
case ACTION_ENABLE_REALTIME_STEPS: {
boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
mDeviceSupport.onEnableRealtimeSteps(enable);
break;
}
case ACTION_ENABLE_HEARTRATE_SLEEP_SUPPORT: {
boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
mDeviceSupport.onEnableHeartRateSleepSupport(enable);
break;
}
case ACTION_SET_HEARTRATE_MEASUREMENT_INTERVAL: {
int seconds = intent.getIntExtra(EXTRA_INTERVAL_SECONDS, 0);
mDeviceSupport.onSetHeartRateMeasurementInterval(seconds);
break;
}
case ACTION_ENABLE_REALTIME_HEARTRATE_MEASUREMENT: {
boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
mDeviceSupport.onEnableRealtimeHeartRateMeasurement(enable);
break;
}
case ACTION_SEND_CONFIGURATION: {
String config = intent.getStringExtra(EXTRA_CONFIG);
mDeviceSupport.onSendConfiguration(config);
break;
}
case ACTION_READ_CONFIGURATION: {
String config = intent.getStringExtra(EXTRA_CONFIG);
mDeviceSupport.onReadConfiguration(config);
break;
}
case ACTION_TEST_NEW_FUNCTION: {
mDeviceSupport.onTestNewFunction();
break;
}
case ACTION_SEND_WEATHER: {
WeatherSpec weatherSpec = intent.getParcelableExtra(EXTRA_WEATHER);
if (weatherSpec != null) {
mDeviceSupport.onSendWeather(weatherSpec);
}
break;
}
case ACTION_SET_LED_COLOR:
int color = intent.getIntExtra(EXTRA_LED_COLOR, 0);
if (color != 0) {
mDeviceSupport.onSetLedColor(color);
}
break;
case ACTION_SET_FM_FREQUENCY:
float frequency = intent.getFloatExtra(EXTRA_FM_FREQUENCY, -1);
if (frequency != -1) {
mDeviceSupport.onSetFmFrequency(frequency);
}
break;
}
}
/**
* Disposes the current DeviceSupport instance (if any) and sets a new device support instance
* (if not null).
*
* @param deviceSupport
*/
private void setDeviceSupport(@Nullable DeviceSupport deviceSupport) {
if (deviceSupport != mDeviceSupport && mDeviceSupport != null) {
mDeviceSupport.dispose();
mDeviceSupport = null;
mGBDevice = null;
mCoordinator = null;
}
mDeviceSupport = deviceSupport;
mGBDevice = mDeviceSupport != null ? mDeviceSupport.getDevice() : null;
mCoordinator = mGBDevice != null ? DeviceHelper.getInstance().getCoordinator(mGBDevice) : null;
}
private void start() {
if (!mStarted) {
startForeground(GB.NOTIFICATION_ID, GB.createNotification(getString(R.string.gadgetbridge_running), this));
mStarted = true;
}
}
public boolean isStarted() {
return mStarted;
}
private boolean isConnected() {
return mGBDevice != null && mGBDevice.isConnected();
}
private boolean isConnecting() {
return mGBDevice != null && mGBDevice.isConnecting();
}
private boolean isInitialized() {
return mGBDevice != null && mGBDevice.isInitialized();
}
private void setReceiversEnableState(boolean enable, boolean initialized, DeviceCoordinator coordinator) {
LOG.info("Setting broadcast receivers to: " + enable);
if (enable && initialized && coordinator != null && coordinator.supportsCalendarEvents()) {
if (mCalendarReceiver == null && getPrefs().getBoolean("enable_calendar_sync", true)) {
if (!(GBApplication.isRunningMarshmallowOrLater() && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_DENIED)) {
IntentFilter calendarIntentFilter = new IntentFilter();
calendarIntentFilter.addAction("android.intent.action.PROVIDER_CHANGED");
calendarIntentFilter.addDataScheme("content");
calendarIntentFilter.addDataAuthority("com.android.calendar", null);
mCalendarReceiver = new CalendarReceiver(mGBDevice);
registerReceiver(mCalendarReceiver, calendarIntentFilter);
}
}
if (mAlarmReceiver == null) {
mAlarmReceiver = new AlarmReceiver();
registerReceiver(mAlarmReceiver, new IntentFilter("DAILY_ALARM"));
}
} else {
if (mCalendarReceiver != null) {
unregisterReceiver(mCalendarReceiver);
mCalendarReceiver = null;
}
if (mAlarmReceiver != null) {
unregisterReceiver(mAlarmReceiver);
mAlarmReceiver = null;
}
}
if (enable) {
if (mPhoneCallReceiver == null) {
mPhoneCallReceiver = new PhoneCallReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
filter.addAction("nodomain.freeyourgadget.gadgetbridge.MUTE_CALL");
registerReceiver(mPhoneCallReceiver, filter);
}
if (mSMSReceiver == null) {
mSMSReceiver = new SMSReceiver();
registerReceiver(mSMSReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
if (mPebbleReceiver == null) {
mPebbleReceiver = new PebbleReceiver();
registerReceiver(mPebbleReceiver, new IntentFilter("com.getpebble.action.SEND_NOTIFICATION"));
}
if (mMusicPlaybackReceiver == null && coordinator != null && coordinator.supportsMusicInfo()) {
mMusicPlaybackReceiver = new MusicPlaybackReceiver();
IntentFilter filter = new IntentFilter();
for (String action : mMusicActions) {
filter.addAction(action);
}
registerReceiver(mMusicPlaybackReceiver, filter);
}
if (mTimeChangeReceiver == null) {
mTimeChangeReceiver = new TimeChangeReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.TIME_SET");
filter.addAction("android.intent.action.TIMEZONE_CHANGED");
registerReceiver(mTimeChangeReceiver, filter);
}
if (mBlueToothConnectReceiver == null) {
mBlueToothConnectReceiver = new BluetoothConnectReceiver(this);
registerReceiver(mBlueToothConnectReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
}
if (mBlueToothPairingRequestReceiver == null) {
mBlueToothPairingRequestReceiver = new BluetoothPairingRequestReceiver(this);
registerReceiver(mBlueToothPairingRequestReceiver, new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST));
}
if (mAlarmClockReceiver == null) {
mAlarmClockReceiver = new AlarmClockReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(AlarmClockReceiver.ALARM_ALERT_ACTION);
filter.addAction(AlarmClockReceiver.ALARM_DONE_ACTION);
filter.addAction(AlarmClockReceiver.GOOGLE_CLOCK_ALARM_ALERT_ACTION);
filter.addAction(AlarmClockReceiver.GOOGLE_CLOCK_ALARM_DONE_ACTION);
registerReceiver(mAlarmClockReceiver, filter);
}
if (mCMWeatherReceiver == null && coordinator != null && coordinator.supportsWeather()) {
mCMWeatherReceiver = new CMWeatherReceiver();
registerReceiver(mCMWeatherReceiver, new IntentFilter("GB_UPDATE_WEATHER"));
}
if (GBApplication.isRunningOreoOrLater()) {
if (mLineageOsWeatherReceiver == null && coordinator != null && coordinator.supportsWeather()) {
mLineageOsWeatherReceiver = new LineageOsWeatherReceiver();
registerReceiver(mLineageOsWeatherReceiver, new IntentFilter("GB_UPDATE_WEATHER"));
}
}
if (mOmniJawsObserver == null && coordinator != null && coordinator.supportsWeather()) {
try {
mOmniJawsObserver = new OmniJawsObserver(new Handler());
getContentResolver().registerContentObserver(OmniJawsObserver.WEATHER_URI, true, mOmniJawsObserver);
} catch (PackageManager.NameNotFoundException e) {
//Nothing wrong, it just means we're not running on omnirom.
}
}
if (GBApplication.getPrefs().getBoolean("auto_fetch_enabled", false) &&
coordinator != null && coordinator.supportsActivityDataFetching() && mGBAutoFetchReceiver == null) {
mGBAutoFetchReceiver = new GBAutoFetchReceiver();
registerReceiver(mGBAutoFetchReceiver, new IntentFilter("android.intent.action.USER_PRESENT"));
}
if (mAutoConnectInvervalReceiver == null) {
mAutoConnectInvervalReceiver= new AutoConnectIntervalReceiver(this);
registerReceiver(mAutoConnectInvervalReceiver, new IntentFilter("GB_RECONNECT"));
}
} else {
if (mPhoneCallReceiver != null) {
unregisterReceiver(mPhoneCallReceiver);
mPhoneCallReceiver = null;
}
if (mSMSReceiver != null) {
unregisterReceiver(mSMSReceiver);
mSMSReceiver = null;
}
if (mPebbleReceiver != null) {
unregisterReceiver(mPebbleReceiver);
mPebbleReceiver = null;
}
if (mMusicPlaybackReceiver != null) {
unregisterReceiver(mMusicPlaybackReceiver);
mMusicPlaybackReceiver = null;
}
if (mTimeChangeReceiver != null) {
unregisterReceiver(mTimeChangeReceiver);
mTimeChangeReceiver = null;
}
if (mBlueToothConnectReceiver != null) {
unregisterReceiver(mBlueToothConnectReceiver);
mBlueToothConnectReceiver = null;
}
if (mBlueToothPairingRequestReceiver != null) {
unregisterReceiver(mBlueToothPairingRequestReceiver);
mBlueToothPairingRequestReceiver = null;
}
if (mAlarmClockReceiver != null) {
unregisterReceiver(mAlarmClockReceiver);
mAlarmClockReceiver = null;
}
if (mCMWeatherReceiver != null) {
unregisterReceiver(mCMWeatherReceiver);
mCMWeatherReceiver = null;
}
if (mLineageOsWeatherReceiver != null) {
unregisterReceiver(mLineageOsWeatherReceiver);
mLineageOsWeatherReceiver = null;
}
if (mOmniJawsObserver != null) {
getContentResolver().unregisterContentObserver(mOmniJawsObserver);
}
if (mGBAutoFetchReceiver != null) {
unregisterReceiver(mGBAutoFetchReceiver);
mGBAutoFetchReceiver = null;
}
if (mAutoConnectInvervalReceiver != null) {
unregisterReceiver(mAutoConnectInvervalReceiver);
mAutoConnectInvervalReceiver = null;
}
}
}
@Override
public void onDestroy() {
if (hasPrefs()) {
getPrefs().getPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
LOG.debug("DeviceCommunicationService is being destroyed");
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
setReceiversEnableState(false, false, null); // disable BroadcastReceivers
setDeviceSupport(null);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (nm != null) {
nm.cancel(GB.NOTIFICATION_ID); // need to do this because the updated notification won't be cancelled when service stops
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (GBPrefs.AUTO_RECONNECT.equals(key)) {
boolean autoReconnect = getGBPrefs().getAutoReconnect();
if (mDeviceSupport != null) {
mDeviceSupport.setAutoReconnect(autoReconnect);
}
}
if (GBPrefs.CHART_MAX_HEART_RATE.equals(key) || GBPrefs.CHART_MIN_HEART_RATE.equals(key)) {
HeartRateUtils.getInstance().updateCachedHeartRatePreferences();
}
}
protected boolean hasPrefs() {
return getPrefs().getPreferences() != null;
}
public Prefs getPrefs() {
return GBApplication.getPrefs();
}
public GBPrefs getGBPrefs() {
return GBApplication.getGBPrefs();
}
public GBDevice getGBDevice() {
return mGBDevice;
}
}
| Huami: Fix stuck in connecting for most cases
This happened when sending a notification while doing authentication.
The reason the notification came though is the "auto connect" code that is
supposed to connect when a message arrives, so that it does not get lost.
This code and DeviceSupport::useAutoConnect() is probably totally useless by now
and could be removed in favor of the "waiting for reconnect" state.
The bug could have been solved by setting the device busy during authentication
in Huami code, but I did it by...
Note to self:
"Block everything except a disconnect request in DeviceCommunicationService
if the device is not yet initialzed but connected, assuming it is somewhere in
the middle doing something important"
| app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/DeviceCommunicationService.java | Huami: Fix stuck in connecting for most cases | <ide><path>pp/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/DeviceCommunicationService.java
<ide> return START_NOT_STICKY;
<ide> }
<ide>
<del> if (mDeviceSupport == null || (!isInitialized() && !mDeviceSupport.useAutoConnect())) {
<add> if (mDeviceSupport == null || (!isInitialized() && !action.equals(ACTION_DISCONNECT) && (!mDeviceSupport.useAutoConnect() || isConnected()))) {
<ide> // trying to send notification without valid Bluetooth connection
<ide> if (mGBDevice != null) {
<ide> // at least send back the current device state |
|
Java | apache-2.0 | 787acc0454cb9e45ee4242ce3cc80631c6cfac60 | 0 | lexs/webimageloader | package se.alexanderblom.imageloader;
import android.content.ContentResolver;
import android.content.Context;
public class URLUtil {
public static String resourceUrl(Context c, int resId) {
return createUrl(ContentResolver.SCHEME_ANDROID_RESOURCE, c.getPackageName(), String.valueOf(resId));
}
public static String assetUrl(String path) {
return createUrl(ContentResolver.SCHEME_FILE, "/android_asset", path);
}
private static String createUrl(String scheme, String authority, String path) {
return scheme + "://" + authority + "/" + path;
}
private URLUtil() {}
}
| imageloader/src/se/alexanderblom/imageloader/URLUtil.java | package se.alexanderblom.imageloader;
import android.content.ContentResolver;
import android.content.Context;
public class URLUtil {
public static String resourceUrl(Context c, int resId) {
return createUrl(ContentResolver.SCHEME_ANDROID_RESOURCE, c.getPackageName(), String.valueOf(resId));
}
public static String assetUrl(String path) {
return createUrl(ContentResolver.SCHEME_FILE, "/android_asset", path);
}
public static String fileUrl(String path) {
return createUrl(ContentResolver.SCHEME_FILE, null, path);
}
private static String createUrl(String scheme, String authority, String path) {
if (authority != null) {
return scheme + "://" + authority + "/" + path;
} else {
return scheme + "://" + path;
}
}
private URLUtil() {}
}
| Remove unnecessary utility method
Clients can use Uri.fromFile() instead
| imageloader/src/se/alexanderblom/imageloader/URLUtil.java | Remove unnecessary utility method | <ide><path>mageloader/src/se/alexanderblom/imageloader/URLUtil.java
<ide> return createUrl(ContentResolver.SCHEME_FILE, "/android_asset", path);
<ide> }
<ide>
<del> public static String fileUrl(String path) {
<del> return createUrl(ContentResolver.SCHEME_FILE, null, path);
<del> }
<del>
<ide> private static String createUrl(String scheme, String authority, String path) {
<del> if (authority != null) {
<del> return scheme + "://" + authority + "/" + path;
<del> } else {
<del> return scheme + "://" + path;
<del> }
<add> return scheme + "://" + authority + "/" + path;
<ide> }
<ide>
<ide> private URLUtil() {} |
|
JavaScript | apache-2.0 | dabacce085278034f9db420f2224125613337c62 | 0 | McLeodMoores/starling,jerome79/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,nssales/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling | /*
* Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
* Please see distribution for license.
*/
$.register_module({
name: 'og.analytics.DropMenu',
dependencies: ['og.common.util.ui.DropMenu'],
obj: function () {
var events = {
queryselected: 'dropmenu:queryselected',
querycancelled: 'dropmenu:querycancelled'
},
DropMenu = function (config) {
/**
* TODO AG: Must provide Getters/Setters for static instance properties as these should
* really be private and not accessible directly via the instance.
*/
var menu = new og.common.util.ui.DropMenu(config), dummy_s = '<wrapper>';
menu.$dom.toggle_prefix = $(dummy_s);
menu.$dom.toggle_infix = $(dummy_s).append('<span>then</span>');
menu.$dom.menu_actions = $('.og-menu-actions', menu.$dom.menu);
menu.$dom.opt = $('.OG-dropmenu-options', menu.$dom.menu);
menu.$dom.opt.data('pos', ((menu.opts = []).push(menu.$dom.opt), menu.opts.length-1));
menu.$dom.add = $('.OG-link-add', menu.$dom.menu);
menu.$dom.opt_cp = menu.$dom.opt.clone(true);
if (menu.$dom.toggle) menu.$dom.toggle.on('click', menu.toggle_menu.bind(menu));
return menu;
};
DropMenu.prototype = og.common.util.ui.DropMenu.prototype;
DropMenu.prototype.toggle_menu = function (event){
this.opts[this.opts.length-1].find('select').first().focus(0);
this.toggle_handler();
};
DropMenu.prototype.add_handler = function () {
var len, opt;
return len = this.opts.length, opt = this.$dom.opt_cp.clone(true).data("pos", this.opts.length),
this.opts.push(opt), this.$dom.add.focus(), this.opts[len].find('.number span').text(this.opts.length),
this.$dom.menu_actions.before(this.opts[len]);
};
DropMenu.prototype.delete_handler = function (elem) {
var data = elem.data();
if (this.opts.length === 1) return;
this.opts.splice(data.pos, 1);
elem.remove();
this.update_opt_nums(data.pos);
if (data.pos < this.opts.length) this.opts[data.pos].find('select').first().focus();
else this.opts[data.pos-1].find('select').first().focus();
};
DropMenu.prototype.update_opt_nums = function (pos) {
for (var i = pos || 0, len = this.opts.length; i < len;)
this.opts[i].data('pos', i).find('.number span').text(i+=1);
};
DropMenu.prototype.sort_opts = function (a, b) {
if (a.pos < b.pos) return -1;
if (a.pos > b.pos) return 1;
return 0;
};
DropMenu.prototype.button_handler = function (val) {
if (val === 'OK') this.emitEvent(this.events.close).emitEvent(events.queryselected, [this]);
else if (val === 'Cancel') this.emitEvent(this.events.close).emitEvent(events.querycancelled, [this]);
};
DropMenu.prototype.capitalize = function (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
return DropMenu;
}
}); | projects/OG-Web/web-engine/prototype/scripts/og/analytics/og.analytics.dropmenu.js | /*
* Copyright 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
* Please see distribution for license.
*/
$.register_module({
name: 'og.analytics.DropMenu',
dependencies: ['og.common.util.ui.DropMenu'],
obj: function () {
var events = {
queryselected: 'dropmenu:queryselected',
querycancelled: 'dropmenu:querycancelled'
},
DropMenu = function (config) {
/**
* TODO AG: Must provide Getters/Setters for static instance properties as these should
* really be private and not accessible directly via the instance.
*/
var menu = new og.common.util.ui.DropMenu(config), dummy_s = '<wrapper>';
menu.$dom.toggle_prefix = $(dummy_s);
menu.$dom.toggle_infix = $(dummy_s).append('<span>then</span>');
menu.$dom.menu_actions = $('.og-menu-actions', menu.$dom.menu);
menu.$dom.opt = $('.OG-dropmenu-options', menu.$dom.menu);
menu.$dom.opt.data('pos', ((menu.opts = []).push(menu.$dom.opt), menu.opts.length-1));
menu.$dom.add = $('.OG-link-add', menu.$dom.menu);
menu.$dom.opt_cp = menu.$dom.opt.clone(true);
if (menu.$dom.toggle) menu.$dom.toggle.on('click', menu.toggle_menu.bind(menu));
return menu;
};
DropMenu.prototype = og.common.util.ui.DropMenu.prototype;
DropMenu.prototype.toggle_menu = function (event){
this.opts[this.opts.length-1].find('select').first().focus();
this.toggle_handler();
};
DropMenu.prototype.add_handler = function () {
return len = this.opts.length, opt = this.$dom.opt_cp.clone(true).data("pos", this.opts.length),
this.opts.push(opt), this.$dom.add.focus(), this.opts[len].find('.number span').text(this.opts.length),
this.$dom.menu_actions.before(this.opts[len]);
};
DropMenu.prototype.delete_handler = function (elem) {
var data = elem.data();
if (this.opts.length === 1) return;
this.opts.splice(data.pos, 1);
elem.remove();
this.update_opt_nums(data.pos);
if (data.pos < this.opts.length) this.opts[data.pos].find('select').first().focus();
else this.opts[data.pos-1].find('select').first().focus();
};
DropMenu.prototype.update_opt_nums = function (pos) {
for (var i = pos || 0, len = this.opts.length; i < len;)
this.opts[i].data('pos', i).find('.number span').text(i+=1);
};
DropMenu.prototype.sort_opts = function (a, b) {
if (a.pos < b.pos) return -1;
if (a.pos > b.pos) return 1;
return 0;
};
DropMenu.prototype.button_handler = function (val) {
if (val === 'OK') this.emitEvent(this.events.close).emitEvent(events.queryselected, [this]);
else if (val === 'Cancel') this.emitEvent(this.events.close).emitEvent(events.querycancelled, [this]);
};
DropMenu.prototype.capitalize = function (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
return DropMenu;
}
}); | focus select fix in DropMenu
| projects/OG-Web/web-engine/prototype/scripts/og/analytics/og.analytics.dropmenu.js | focus select fix in DropMenu | <ide><path>rojects/OG-Web/web-engine/prototype/scripts/og/analytics/og.analytics.dropmenu.js
<ide> };
<ide> DropMenu.prototype = og.common.util.ui.DropMenu.prototype;
<ide> DropMenu.prototype.toggle_menu = function (event){
<del> this.opts[this.opts.length-1].find('select').first().focus();
<add> this.opts[this.opts.length-1].find('select').first().focus(0);
<ide> this.toggle_handler();
<ide> };
<ide> DropMenu.prototype.add_handler = function () {
<add> var len, opt;
<ide> return len = this.opts.length, opt = this.$dom.opt_cp.clone(true).data("pos", this.opts.length),
<ide> this.opts.push(opt), this.$dom.add.focus(), this.opts[len].find('.number span').text(this.opts.length),
<ide> this.$dom.menu_actions.before(this.opts[len]); |
|
Java | apache-2.0 | 22379210a023720ceb127211adce911e4557f43b | 0 | rozza/mongo-java-driver,jyemin/mongo-java-driver,jsonking/mongo-java-driver,kay-kim/mongo-java-driver,gianpaj/mongo-java-driver,PSCGroup/mongo-java-driver,jsonking/mongo-java-driver,jyemin/mongo-java-driver,rozza/mongo-java-driver | /*
* Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import org.mongodb.Codec;
import org.mongodb.Document;
import org.mongodb.annotations.ThreadSafe;
import org.mongodb.codecs.DocumentCodec;
import org.mongodb.codecs.PrimitiveCodecs;
import org.mongodb.command.ListDatabases;
import org.mongodb.connection.BufferProvider;
import org.mongodb.connection.Cluster;
import org.mongodb.connection.ClusterDescription;
import org.mongodb.connection.ClusterableServerFactory;
import org.mongodb.connection.ConnectionFactory;
import org.mongodb.connection.SSLSettings;
import org.mongodb.connection.ServerDescription;
import org.mongodb.connection.impl.DefaultClusterFactory;
import org.mongodb.connection.impl.DefaultClusterableServerFactory;
import org.mongodb.connection.impl.DefaultConnectionFactory;
import org.mongodb.connection.impl.DefaultConnectionProviderFactory;
import org.mongodb.connection.impl.DefaultConnectionProviderSettings;
import org.mongodb.connection.impl.DefaultConnectionSettings;
import org.mongodb.connection.impl.DefaultServerSettings;
import org.mongodb.connection.impl.PowerOfTwoBufferPool;
import org.mongodb.session.ClusterSession;
import org.mongodb.session.PinnedSession;
import org.mongodb.session.ServerSelectingSession;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static com.mongodb.MongoExceptions.mapException;
import static org.mongodb.assertions.Assertions.isTrue;
import static org.mongodb.connection.ClusterConnectionMode.Discovering;
import static org.mongodb.connection.ClusterType.ReplicaSet;
@ThreadSafe
public class Mongo {
static final String ADMIN_DATABASE_NAME = "admin";
private static final String VERSION = "3.0.0-SNAPSHOT";
private final ConcurrentMap<String, DB> dbCache = new ConcurrentHashMap<String, DB>();
private volatile WriteConcern writeConcern;
private volatile ReadPreference readPreference;
private final Bytes.OptionHolder optionHolder;
private final Codec<Document> documentCodec;
private final Cluster cluster;
private final BufferProvider bufferProvider = new PowerOfTwoBufferPool();
private final ThreadLocal<ServerSelectingSession> pinnedSession = new ThreadLocal<ServerSelectingSession>();
Mongo(final List<ServerAddress> seedList, final MongoClientOptions mongoOptions) {
this(new DefaultClusterFactory().create(createNewSeedList(seedList), createClusterableServerFactory(mongoOptions.toNew())),
mongoOptions);
}
Mongo(final MongoClientURI mongoURI) throws UnknownHostException {
this(createCluster(mongoURI.toNew()), mongoURI.getOptions());
}
Mongo(final ServerAddress serverAddress, final MongoClientOptions mongoOptions) {
this(new DefaultClusterFactory().create(serverAddress.toNew(), createClusterableServerFactory(mongoOptions.toNew())), mongoOptions);
}
public Mongo(final ServerAddress addr, final List<MongoCredential> credentialsList, final MongoClientOptions options) {
this(new DefaultClusterFactory().create(addr.toNew(), createClusterableServerFactory(createNewCredentialList(credentialsList),
options.toNew())), options);
}
Mongo(final List<ServerAddress> seedList, final List<MongoCredential> credentialsList, final MongoClientOptions options) {
this(new DefaultClusterFactory().create(createNewSeedList(seedList),
createClusterableServerFactory(createNewCredentialList(credentialsList), options.toNew())), options);
}
Mongo(final Cluster cluster, final MongoClientOptions options) {
this.cluster = cluster;
this.documentCodec = new DocumentCodec(PrimitiveCodecs.createDefault());
this.readPreference = options.getReadPreference() != null ?
options.getReadPreference() : ReadPreference.primary();
this.writeConcern = options.getWriteConcern() != null ?
options.getWriteConcern() : WriteConcern.UNACKNOWLEDGED;
this.optionHolder = new Bytes.OptionHolder(null);
}
/**
* Sets the write concern for this database. Will be used as default for writes to any collection in any database.
* See the documentation for {@link WriteConcern} for more information.
*
* @param writeConcern write concern to use
*/
public void setWriteConcern(final WriteConcern writeConcern) {
this.writeConcern = writeConcern;
}
/**
* Gets the default write concern
*
* @return the default write concern
*/
public WriteConcern getWriteConcern() {
return writeConcern;
}
/**
* Sets the read preference for this database. Will be used as default for reads from any collection in any
* database. See the documentation for {@link ReadPreference} for more information.
*
* @param readPreference Read Preference to use
*/
public void setReadPreference(final ReadPreference readPreference) {
this.readPreference = readPreference;
}
/**
* Gets the default read preference
*
* @return the default read preference
*/
public ReadPreference getReadPreference() {
return readPreference;
}
/**
* Gets the current driver version.
*
* @return the full version string, e.g. "3.0.0"
*/
public static String getVersion() {
return VERSION;
}
/**
* Gets a list of all server addresses used when this Mongo was created
*
* @return list of server addresses
* @throws MongoException
*/
public List<ServerAddress> getAllAddress() {
//TODO It should return the address list without auto-discovered nodes. Not sure if it's required. Maybe users confused with name.
return getServerAddressList();
}
/**
* Gets the list of server addresses currently seen by this client. This includes addresses auto-discovered from a
* replica set.
*
* @return list of server addresses
* @throws MongoException
*/
public List<ServerAddress> getServerAddressList() {
final List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
for (final ServerDescription cur : getClusterDescription().getAll()) {
serverAddresses.add(new ServerAddress(cur.getAddress()));
}
return serverAddresses;
}
private ClusterDescription getClusterDescription(){
try {
return cluster.getDescription();
} catch (org.mongodb.MongoException e) {
//TODO: test this
throw mapException(e);
}
}
/**
* Gets the address of the current master
*
* @return the address
*/
public ServerAddress getAddress() {
final ClusterDescription description = getClusterDescription();
if (description.getPrimaries().isEmpty()) {
return null;
}
return new ServerAddress(description.getPrimaries().get(0).getAddress());
}
/**
* Get the status of the replica set cluster.
*
* @return replica set status information
*/
public ReplicaSetStatus getReplicaSetStatus() {
return getClusterDescription().getType() == ReplicaSet && getClusterDescription().getMode() == Discovering
? new ReplicaSetStatus(cluster) : null; // this is intended behavior in 2.x
}
/**
* Gets a list of the names of all databases on the connected server.
*
* @return list of database names
* @throws MongoException
*/
public List<String> getDatabaseNames() {
//TODO: how do I make sure the exception is wrapped correctly?
final org.mongodb.operation.CommandResult listDatabasesResult;
listDatabasesResult = getDB(ADMIN_DATABASE_NAME).executeCommand(new ListDatabases());
@SuppressWarnings("unchecked")
final List<Document> databases = (List<Document>) listDatabasesResult.getResponse().get("databases");
final List<String> databaseNames = new ArrayList<String>();
for (final Document d : databases) {
databaseNames.add(d.get("name", String.class));
}
return Collections.unmodifiableList(databaseNames);
}
/**
* Gets a database object
*
* @param dbName the name of the database to retrieve
* @return a DB representing the specified database
*/
public DB getDB(final String dbName) {
DB db = dbCache.get(dbName);
if (db != null) {
return db;
}
db = new DB(this, dbName, documentCodec);
final DB temp = dbCache.putIfAbsent(dbName, db);
if (temp != null) {
return temp;
}
return db;
}
/**
* Returns the list of databases used by the driver since this Mongo instance was created.
* This may include DBs that exist in the client but not yet on the server.
*
* @return a collection of database objects
*/
public Collection<DB> getUsedDatabases() {
return dbCache.values();
}
/**
* Drops the database if it exists.
*
* @param dbName name of database to drop
* @throws MongoException
*/
public void dropDatabase(final String dbName) {
getDB(dbName).dropDatabase();
}
/**
* Closes all resources associated with this instance, in particular any open network connections. Once called, this
* instance and any databases obtained from it can no longer be used.
*/
public void close() {
cluster.close();
}
/**
* Makes it possible to run read queries on secondary nodes
*
* @see ReadPreference#secondaryPreferred()
* @deprecated Replaced with {@code ReadPreference.secondaryPreferred()}
*/
@Deprecated
public void slaveOk() {
addOption(Bytes.QUERYOPTION_SLAVEOK);
}
/**
* Set the default query options.
*
* @param options value to be set
*/
public void setOptions(final int options) {
optionHolder.set(options);
}
/**
* Reset the default query options.
*/
public void resetOptions() {
optionHolder.reset();
}
/**
* Add the default query option.
*
* @param option value to be added to current options
*/
public void addOption(final int option) {
optionHolder.add(option);
}
public int getOptions() {
return optionHolder.get();
}
/**
* Forces the master server to fsync the RAM data to disk
* This is done automatically by the server at intervals, but can be forced for better reliability.
* @param async if true, the fsync will be done asynchronously on the server.
* @return result of the command execution
* @throws MongoException
*/
public CommandResult fsync(boolean async) {
final DBObject command = new BasicDBObject("fsync", 1);
if (async) {
command.put("async", 1);
}
return getDB(ADMIN_DATABASE_NAME).command(command);
}
/**
* Forces the master server to fsync the RAM data to disk, then lock all writes.
* The database will be read-only after this command returns.
* @return result of the command execution
* @throws MongoException
*/
public CommandResult fsyncAndLock() {
final DBObject command = new BasicDBObject("fsync", 1);
command.put("lock", 1);
return getDB(ADMIN_DATABASE_NAME).command(command);
}
/**
* Unlocks the database, allowing the write operations to go through.
* This command may be asynchronous on the server, which means there may be a small delay before the database becomes writable.
* @return {@code DBObject} in the following form {@code {"ok": 1,"info": "unlock completed"}}
* @throws MongoException
*/
public DBObject unlock() {
return getDB(ADMIN_DATABASE_NAME).getCollection("$cmd.sys.unlock").findOne();
}
/**
* Returns true if the database is locked (read-only), false otherwise.
* @return result of the command execution
* @throws MongoException
*/
public boolean isLocked() {
final DBCollection inprogCollection = getDB(ADMIN_DATABASE_NAME).getCollection("$cmd.sys.inprog");
final BasicDBObject result = (BasicDBObject) inprogCollection.findOne();
return result.containsField("fsyncLock")
? result.getInt("fsyncLock") == 1
: false;
}
@Override
public String toString() {
return "Mongo{" +
"VERSION='" + VERSION + '\'' +
", options=" + getOptions() +
'}';
}
/**
* Gets the maximum size for a BSON object supported by the current master server.
* Note that this value may change over time depending on which server is master.
*
* @return the maximum size, or 0 if not obtained from servers yet.
* @throws MongoException
*/
public int getMaxBsonObjectSize() {
final List<ServerDescription> primaries = getClusterDescription().getPrimaries();
return primaries.isEmpty() ? ServerDescription.getDefaultMaxDocumentSize() : primaries.get(0).getMaxDocumentSize();
}
/**
* Gets a {@code String} representation of current connection point, i.e. master.
* @return server address in a host:port form
*/
public String getConnectPoint(){
final ServerAddress master = getAddress();
return master != null ? String.format("%s:%d", master.getHost(), master.getPort()) : null;
}
private static List<org.mongodb.connection.ServerAddress> createNewSeedList(final List<ServerAddress> seedList) {
final List<org.mongodb.connection.ServerAddress> retVal = new ArrayList<org.mongodb.connection.ServerAddress>(seedList.size());
for (final ServerAddress cur : seedList) {
retVal.add(cur.toNew());
}
return retVal;
}
private static List<org.mongodb.MongoCredential> createNewCredentialList(final List<MongoCredential> credentialsList) {
if (credentialsList == null) {
return Collections.emptyList();
}
final List<org.mongodb.MongoCredential> retVal = new ArrayList<org.mongodb.MongoCredential>(credentialsList.size());
for (final MongoCredential cur : credentialsList) {
retVal.add(cur.toNew());
}
return retVal;
}
private static Cluster createCluster(final org.mongodb.MongoClientURI mongoURI) throws UnknownHostException {
if (mongoURI.getHosts().size() == 1) {
return new DefaultClusterFactory().create(new org.mongodb.connection.ServerAddress(mongoURI.getHosts().get(0)),
createClusterableServerFactory(mongoURI.getCredentialList(), mongoURI.getOptions()));
}
else {
final List<org.mongodb.connection.ServerAddress> seedList = new ArrayList<org.mongodb.connection.ServerAddress>();
for (final String cur : mongoURI.getHosts()) {
seedList.add(new org.mongodb.connection.ServerAddress(cur));
}
return new DefaultClusterFactory().create(seedList, createClusterableServerFactory(mongoURI.getCredentialList(),
mongoURI.getOptions()));
}
}
private static ClusterableServerFactory createClusterableServerFactory(final org.mongodb.MongoClientOptions options) {
return createClusterableServerFactory(Collections.<org.mongodb.MongoCredential>emptyList(), options);
}
private static ClusterableServerFactory createClusterableServerFactory(final List<org.mongodb.MongoCredential> credentialList,
final org.mongodb.MongoClientOptions options) {
final BufferProvider bufferProvider = new PowerOfTwoBufferPool();
final SSLSettings sslSettings = SSLSettings.builder().enabled(options.isSSLEnabled()).build();
final DefaultConnectionProviderSettings connectionProviderSettings = DefaultConnectionProviderSettings.builder()
.maxSize(options.getConnectionsPerHost())
.maxWaitQueueSize(options.getConnectionsPerHost() * options.getThreadsAllowedToBlockForConnectionMultiplier())
.maxWaitTime(options.getMaxWaitTime(), TimeUnit.MILLISECONDS)
.build();
final DefaultConnectionSettings connectionSettings = DefaultConnectionSettings.builder()
.connectTimeoutMS(options.getConnectTimeout())
.readTimeoutMS(options.getSocketTimeout())
.keepAlive(options.isSocketKeepAlive())
.build();
final ConnectionFactory connectionFactory = new DefaultConnectionFactory(connectionSettings, sslSettings, bufferProvider, credentialList);
return new DefaultClusterableServerFactory(
DefaultServerSettings.builder()
.heartbeatFrequency(Integer.parseInt(System.getProperty("com.mongodb.updaterIntervalMS", "5000")),
TimeUnit.MILLISECONDS)
.build(),
new DefaultConnectionProviderFactory(connectionProviderSettings, connectionFactory),
null,
new DefaultConnectionFactory(
DefaultConnectionSettings.builder()
.connectTimeoutMS(Integer.parseInt(System.getProperty("com.mongodb.updaterConnectTimeoutMS", "20000")))
.readTimeoutMS(Integer.parseInt(System.getProperty("com.mongodb.updaterSocketTimeoutMS", "20000")))
.keepAlive(options.isSocketKeepAlive())
.build(),
sslSettings, bufferProvider, credentialList),
Executors.newScheduledThreadPool(3), // TODO: allow configuration
bufferProvider);
}
Cluster getCluster() {
return cluster;
}
Bytes.OptionHolder getOptionHolder() {
return optionHolder;
}
BufferProvider getBufferProvider() {
return bufferProvider;
}
ServerSelectingSession getSession() {
if (pinnedSession.get() != null) {
return pinnedSession.get();
}
return new ClusterSession(getCluster());
}
void pinSession() {
isTrue("request not already started", pinnedSession.get() == null);
pinnedSession.set(new PinnedSession(cluster));
}
void unpinSession() {
isTrue("request started", pinnedSession.get() != null);
final ServerSelectingSession sessionToUnpin = this.pinnedSession.get();
this.pinnedSession.remove();
sessionToUnpin.close();
}
}
| driver-compat/src/main/com/mongodb/Mongo.java | /*
* Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import org.mongodb.Codec;
import org.mongodb.Document;
import org.mongodb.annotations.ThreadSafe;
import org.mongodb.codecs.DocumentCodec;
import org.mongodb.codecs.PrimitiveCodecs;
import org.mongodb.command.ListDatabases;
import org.mongodb.connection.BufferProvider;
import org.mongodb.connection.Cluster;
import org.mongodb.connection.ClusterDescription;
import org.mongodb.connection.ClusterableServerFactory;
import org.mongodb.connection.ConnectionFactory;
import org.mongodb.connection.SSLSettings;
import org.mongodb.connection.ServerDescription;
import org.mongodb.connection.impl.DefaultClusterFactory;
import org.mongodb.connection.impl.DefaultClusterableServerFactory;
import org.mongodb.connection.impl.DefaultConnectionFactory;
import org.mongodb.connection.impl.DefaultConnectionProviderFactory;
import org.mongodb.connection.impl.DefaultConnectionProviderSettings;
import org.mongodb.connection.impl.DefaultConnectionSettings;
import org.mongodb.connection.impl.DefaultServerSettings;
import org.mongodb.connection.impl.PowerOfTwoBufferPool;
import org.mongodb.session.ClusterSession;
import org.mongodb.session.PinnedSession;
import org.mongodb.session.ServerSelectingSession;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static com.mongodb.MongoExceptions.mapException;
import static org.mongodb.assertions.Assertions.isTrue;
import static org.mongodb.connection.ClusterConnectionMode.Discovering;
import static org.mongodb.connection.ClusterType.ReplicaSet;
@ThreadSafe
public class Mongo {
static final String ADMIN_DATABASE_NAME = "admin";
private static final String VERSION = "3.0.0-SNAPSHOT";
private final ConcurrentMap<String, DB> dbCache = new ConcurrentHashMap<String, DB>();
private volatile WriteConcern writeConcern;
private volatile ReadPreference readPreference;
private final Bytes.OptionHolder optionHolder;
private final Codec<Document> documentCodec;
private final Cluster cluster;
private final BufferProvider bufferProvider = new PowerOfTwoBufferPool();
private final ThreadLocal<ServerSelectingSession> pinnedSession = new ThreadLocal<ServerSelectingSession>();
Mongo(final List<ServerAddress> seedList, final MongoClientOptions mongoOptions) {
this(new DefaultClusterFactory().create(createNewSeedList(seedList), createClusterableServerFactory(mongoOptions.toNew())),
mongoOptions);
}
Mongo(final MongoClientURI mongoURI) throws UnknownHostException {
this(createCluster(mongoURI.toNew()), mongoURI.getOptions());
}
Mongo(final ServerAddress serverAddress, final MongoClientOptions mongoOptions) {
this(new DefaultClusterFactory().create(serverAddress.toNew(), createClusterableServerFactory(mongoOptions.toNew())), mongoOptions);
}
public Mongo(final ServerAddress addr, final List<MongoCredential> credentialsList, final MongoClientOptions options) {
this(new DefaultClusterFactory().create(addr.toNew(), createClusterableServerFactory(createNewCredentialList(credentialsList),
options.toNew())), options);
}
Mongo(final List<ServerAddress> seedList, final List<MongoCredential> credentialsList, final MongoClientOptions options) {
this(new DefaultClusterFactory().create(createNewSeedList(seedList),
createClusterableServerFactory(createNewCredentialList(credentialsList), options.toNew())), options);
}
Mongo(final Cluster cluster, final MongoClientOptions options) {
this.cluster = cluster;
this.documentCodec = new DocumentCodec(PrimitiveCodecs.createDefault());
this.readPreference = options.getReadPreference() != null ?
options.getReadPreference() : ReadPreference.primary();
this.writeConcern = options.getWriteConcern() != null ?
options.getWriteConcern() : WriteConcern.UNACKNOWLEDGED;
this.optionHolder = new Bytes.OptionHolder(null);
}
/**
* Sets the write concern for this database. Will be used as default for writes to any collection in any database.
* See the documentation for {@link WriteConcern} for more information.
*
* @param writeConcern write concern to use
*/
public void setWriteConcern(final WriteConcern writeConcern) {
this.writeConcern = writeConcern;
}
/**
* Gets the default write concern
*
* @return the default write concern
*/
public WriteConcern getWriteConcern() {
return writeConcern;
}
/**
* Sets the read preference for this database. Will be used as default for reads from any collection in any
* database. See the documentation for {@link ReadPreference} for more information.
*
* @param readPreference Read Preference to use
*/
public void setReadPreference(final ReadPreference readPreference) {
this.readPreference = readPreference;
}
/**
* Gets the default read preference
*
* @return the default read preference
*/
public ReadPreference getReadPreference() {
return readPreference;
}
/**
* Gets the current driver version.
*
* @return the full version string, e.g. "3.0.0"
*/
public static String getVersion() {
return VERSION;
}
/**
* Gets a list of all server addresses used when this Mongo was created
*
* @return list of server addresses
* @throws MongoException
*/
public List<ServerAddress> getAllAddress() {
//TODO It should return the address list without auto-discovered nodes. Not sure if it's required. Maybe users confused with name.
return getServerAddressList();
}
/**
* Gets the list of server addresses currently seen by this client. This includes addresses auto-discovered from a
* replica set.
*
* @return list of server addresses
* @throws MongoException
*/
public List<ServerAddress> getServerAddressList() {
final List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
for (final ServerDescription cur : getClusterDescription().getAll()) {
serverAddresses.add(new ServerAddress(cur.getAddress()));
}
return serverAddresses;
}
private ClusterDescription getClusterDescription(){
try {
return cluster.getDescription();
} catch (org.mongodb.MongoException e) {
//TODO: test this
throw mapException(e);
}
}
/**
* Gets the address of the current master
*
* @return the address
*/
public ServerAddress getAddress() {
final ClusterDescription description = getClusterDescription();
if (description.getPrimaries().isEmpty()) {
return null;
}
return new ServerAddress(description.getPrimaries().get(0).getAddress());
}
/**
* Get the status of the replica set cluster.
*
* @return replica set status information
*/
public ReplicaSetStatus getReplicaSetStatus() {
return getClusterDescription().getType() == ReplicaSet && getClusterDescription().getMode() == Discovering
? new ReplicaSetStatus(cluster) : null; // this is intended behavior in 2.x
}
/**
* Gets a list of the names of all databases on the connected server.
*
* @return list of database names
* @throws MongoException
*/
public List<String> getDatabaseNames() {
//TODO: how do I make sure the exception is wrapped correctly?
final org.mongodb.operation.CommandResult listDatabasesResult;
listDatabasesResult = getDB(ADMIN_DATABASE_NAME).executeCommand(new ListDatabases());
@SuppressWarnings("unchecked")
final List<Document> databases = (List<Document>) listDatabasesResult.getResponse().get("databases");
final List<String> databaseNames = new ArrayList<String>();
for (final Document d : databases) {
databaseNames.add(d.get("name", String.class));
}
return Collections.unmodifiableList(databaseNames);
}
/**
* Gets a database object
*
* @param dbName the name of the database to retrieve
* @return a DB representing the specified database
*/
public DB getDB(final String dbName) {
DB db = dbCache.get(dbName);
if (db != null) {
return db;
}
db = new DB(this, dbName, documentCodec);
final DB temp = dbCache.putIfAbsent(dbName, db);
if (temp != null) {
return temp;
}
return db;
}
/**
* Returns the list of databases used by the driver since this Mongo instance was created.
* This may include DBs that exist in the client but not yet on the server.
*
* @return a collection of database objects
*/
public Collection<DB> getUsedDatabases() {
return dbCache.values();
}
/**
* Drops the database if it exists.
*
* @param dbName name of database to drop
* @throws MongoException
*/
public void dropDatabase(final String dbName) {
getDB(dbName).dropDatabase();
}
/**
* Closes all resources associated with this instance, in particular any open network connections. Once called, this
* instance and any databases obtained from it can no longer be used.
*/
public void close() {
cluster.close();
}
/**
* Makes it possible to run read queries on secondary nodes
*
* @see ReadPreference#secondaryPreferred()
* @deprecated Replaced with {@code ReadPreference.secondaryPreferred()}
*/
@Deprecated
public void slaveOk() {
addOption(Bytes.QUERYOPTION_SLAVEOK);
}
/**
* Set the default query options.
*
* @param options value to be set
*/
public void setOptions(final int options) {
optionHolder.set(options);
}
/**
* Reset the default query options.
*/
public void resetOptions() {
optionHolder.reset();
}
/**
* Add the default query option.
*
* @param option value to be added to current options
*/
public void addOption(final int option) {
optionHolder.add(option);
}
public int getOptions() {
return optionHolder.get();
}
/**
* Forces the master server to fsync the RAM data to disk
* This is done automatically by the server at intervals, but can be forced for better reliability.
* @param async if true, the fsync will be done asynchronously on the server.
* @return result of the command execution
* @throws MongoException
*/
public CommandResult fsync(boolean async) {
final DBObject command = new BasicDBObject("fsync", 1);
if (async) {
command.put("async", 1);
}
return getDB(ADMIN_DATABASE_NAME).command(command);
}
/**
* Forces the master server to fsync the RAM data to disk, then lock all writes.
* The database will be read-only after this command returns.
* @return result of the command execution
* @throws MongoException
*/
public CommandResult fsyncAndLock() {
final DBObject command = new BasicDBObject("fsync", 1);
command.put("lock", 1);
return getDB(ADMIN_DATABASE_NAME).command(command);
}
/**
* Unlocks the database, allowing the write operations to go through.
* This command may be asynchronous on the server, which means there may be a small delay before the database becomes writable.
* @return {@code DBObject} in the following form {@code {"ok": 1,"info": "unlock completed"}}
* @throws MongoException
*/
public DBObject unlock() {
return getDB(ADMIN_DATABASE_NAME).getCollection("$cmd.sys.unlock").findOne();
}
/**
* Returns true if the database is locked (read-only), false otherwise.
* @return result of the command execution
* @throws MongoException
*/
public boolean isLocked() {
final DBCollection inprogCollection = getDB(ADMIN_DATABASE_NAME).getCollection("$cmd.sys.inprog");
final BasicDBObject result = (BasicDBObject) inprogCollection.findOne();
return result.containsField("fsyncLock")
? result.getInt("fsyncLock") == 1
: false;
}
@Override
public String toString() {
return "Mongo{" +
"VERSION='" + VERSION + '\'' +
", options=" + getOptions() +
'}';
}
private static List<org.mongodb.connection.ServerAddress> createNewSeedList(final List<ServerAddress> seedList) {
final List<org.mongodb.connection.ServerAddress> retVal = new ArrayList<org.mongodb.connection.ServerAddress>(seedList.size());
for (final ServerAddress cur : seedList) {
retVal.add(cur.toNew());
}
return retVal;
}
private static List<org.mongodb.MongoCredential> createNewCredentialList(final List<MongoCredential> credentialsList) {
if (credentialsList == null) {
return Collections.emptyList();
}
final List<org.mongodb.MongoCredential> retVal = new ArrayList<org.mongodb.MongoCredential>(credentialsList.size());
for (final MongoCredential cur : credentialsList) {
retVal.add(cur.toNew());
}
return retVal;
}
private static Cluster createCluster(final org.mongodb.MongoClientURI mongoURI) throws UnknownHostException {
if (mongoURI.getHosts().size() == 1) {
return new DefaultClusterFactory().create(new org.mongodb.connection.ServerAddress(mongoURI.getHosts().get(0)),
createClusterableServerFactory(mongoURI.getCredentialList(), mongoURI.getOptions()));
}
else {
final List<org.mongodb.connection.ServerAddress> seedList = new ArrayList<org.mongodb.connection.ServerAddress>();
for (final String cur : mongoURI.getHosts()) {
seedList.add(new org.mongodb.connection.ServerAddress(cur));
}
return new DefaultClusterFactory().create(seedList, createClusterableServerFactory(mongoURI.getCredentialList(),
mongoURI.getOptions()));
}
}
private static ClusterableServerFactory createClusterableServerFactory(final org.mongodb.MongoClientOptions options) {
return createClusterableServerFactory(Collections.<org.mongodb.MongoCredential>emptyList(), options);
}
private static ClusterableServerFactory createClusterableServerFactory(final List<org.mongodb.MongoCredential> credentialList,
final org.mongodb.MongoClientOptions options) {
final BufferProvider bufferProvider = new PowerOfTwoBufferPool();
final SSLSettings sslSettings = SSLSettings.builder().enabled(options.isSSLEnabled()).build();
final DefaultConnectionProviderSettings connectionProviderSettings = DefaultConnectionProviderSettings.builder()
.maxSize(options.getConnectionsPerHost())
.maxWaitQueueSize(options.getConnectionsPerHost() * options.getThreadsAllowedToBlockForConnectionMultiplier())
.maxWaitTime(options.getMaxWaitTime(), TimeUnit.MILLISECONDS)
.build();
final DefaultConnectionSettings connectionSettings = DefaultConnectionSettings.builder()
.connectTimeoutMS(options.getConnectTimeout())
.readTimeoutMS(options.getSocketTimeout())
.keepAlive(options.isSocketKeepAlive())
.build();
final ConnectionFactory connectionFactory = new DefaultConnectionFactory(connectionSettings, sslSettings, bufferProvider, credentialList);
return new DefaultClusterableServerFactory(
DefaultServerSettings.builder()
.heartbeatFrequency(Integer.parseInt(System.getProperty("com.mongodb.updaterIntervalMS", "5000")),
TimeUnit.MILLISECONDS)
.build(),
new DefaultConnectionProviderFactory(connectionProviderSettings, connectionFactory),
null,
new DefaultConnectionFactory(
DefaultConnectionSettings.builder()
.connectTimeoutMS(Integer.parseInt(System.getProperty("com.mongodb.updaterConnectTimeoutMS", "20000")))
.readTimeoutMS(Integer.parseInt(System.getProperty("com.mongodb.updaterSocketTimeoutMS", "20000")))
.keepAlive(options.isSocketKeepAlive())
.build(),
sslSettings, bufferProvider, credentialList),
Executors.newScheduledThreadPool(3), // TODO: allow configuration
bufferProvider);
}
Cluster getCluster() {
return cluster;
}
Bytes.OptionHolder getOptionHolder() {
return optionHolder;
}
BufferProvider getBufferProvider() {
return bufferProvider;
}
ServerSelectingSession getSession() {
if (pinnedSession.get() != null) {
return pinnedSession.get();
}
return new ClusterSession(getCluster());
}
void pinSession() {
isTrue("request not already started", pinnedSession.get() == null);
pinnedSession.set(new PinnedSession(cluster));
}
void unpinSession() {
isTrue("request started", pinnedSession.get() != null);
final ServerSelectingSession sessionToUnpin = this.pinnedSession.get();
this.pinnedSession.remove();
sessionToUnpin.close();
}
}
| chore(driver-compat) add back c.m.Mongo.{getMaxBsonObjectSize, getConnectPoint}
| driver-compat/src/main/com/mongodb/Mongo.java | chore(driver-compat) add back c.m.Mongo.{getMaxBsonObjectSize, getConnectPoint} | <ide><path>river-compat/src/main/com/mongodb/Mongo.java
<ide> '}';
<ide> }
<ide>
<add> /**
<add> * Gets the maximum size for a BSON object supported by the current master server.
<add> * Note that this value may change over time depending on which server is master.
<add> *
<add> * @return the maximum size, or 0 if not obtained from servers yet.
<add> * @throws MongoException
<add> */
<add> public int getMaxBsonObjectSize() {
<add> final List<ServerDescription> primaries = getClusterDescription().getPrimaries();
<add> return primaries.isEmpty() ? ServerDescription.getDefaultMaxDocumentSize() : primaries.get(0).getMaxDocumentSize();
<add> }
<add>
<add> /**
<add> * Gets a {@code String} representation of current connection point, i.e. master.
<add> * @return server address in a host:port form
<add> */
<add> public String getConnectPoint(){
<add> final ServerAddress master = getAddress();
<add> return master != null ? String.format("%s:%d", master.getHost(), master.getPort()) : null;
<add> }
<add>
<ide> private static List<org.mongodb.connection.ServerAddress> createNewSeedList(final List<ServerAddress> seedList) {
<ide> final List<org.mongodb.connection.ServerAddress> retVal = new ArrayList<org.mongodb.connection.ServerAddress>(seedList.size());
<ide> for (final ServerAddress cur : seedList) { |
|
Java | mit | ebc054fdaa5363d3a7e8167400763aead331b33c | 0 | TulevaEE/onboarding-service,TulevaEE/onboarding-service,TulevaEE/onboarding-service,TulevaEE/onboarding-service | package ee.tuleva.onboarding.account;
import ee.eesti.xtee6.kpr.PensionAccountBalanceResponseType;
import ee.eesti.xtee6.kpr.PensionAccountBalanceType;
import ee.eesti.xtee6.kpr.PersonalSelectionResponseType;
import ee.tuleva.onboarding.auth.principal.Person;
import ee.tuleva.onboarding.fund.Fund;
import ee.tuleva.onboarding.fund.FundRepository;
import ee.tuleva.onboarding.kpr.KPRClient;
import ee.tuleva.onboarding.mandate.statistics.FundValueStatistics;
import ee.tuleva.onboarding.mandate.statistics.FundValueStatisticsRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class AccountStatementService {
private final KPRClient kprClient;
private final FundRepository fundRepository;
private final KPRUnitsOsakudToFundBalanceConverter kprUnitsOsakudToFundBalanceConverter;
private final FundValueStatisticsRepository fundValueStatisticsRepository;
// @Cacheable(value="balances", key="#person.personalCode.CASE_INSENSITIVE_ORDER")
public List<FundBalance> getMyPensionAccountStatement(Person person, UUID statisticsIdentifier) {
log.info("Getting pension account statement for {} {}", person.getFirstName(), person.getLastName());
List<FundBalance> fundBalances = convertXRoadResponse(getPensionAccountBalance(person));
fundBalances = handleActiveFundBalance(fundBalances, getActiveFundName(person));
saveFundValueStatistics(fundBalances, statisticsIdentifier);
return fundBalances;
}
private void saveFundValueStatistics(List<FundBalance> fundBalances, UUID fundValueStatisticsIdentifier) {
fundBalances.stream().map( fundBalance -> FundValueStatistics.builder()
.isin(fundBalance.getFund().getIsin())
.value(fundBalance.getValue())
.identifier(fundValueStatisticsIdentifier)
.build())
.forEach(fundValueStatisticsRepository::save);
}
private PensionAccountBalanceResponseType getPensionAccountBalance(Person person) {
PensionAccountBalanceType request = new PensionAccountBalanceType();
request.setBalanceDate(null);
return kprClient.pensionAccountBalance(request, person.getPersonalCode());
}
private List<FundBalance> convertXRoadResponse(PensionAccountBalanceResponseType response) {
return
response.getUnits().getBalance().stream()
.map(kprUnitsOsakudToFundBalanceConverter::convert)
.collect(Collectors.toList());
}
private String getActiveFundName(Person person) {
PersonalSelectionResponseType csdPersonalSelection = kprClient.personalSelection(person.getPersonalCode());
String activeFundName = csdPersonalSelection.getPensionAccount().getSecurityName();
log.info("Active fund name is {}", activeFundName);
return activeFundName;
}
private List<FundBalance> handleActiveFundBalance(List<FundBalance> fundBalances, String activeFundName) {
fundBalances.stream().forEach( fb-> {
log.info("Having fund {} with isin {}",
fb.getFund().getName(), fb.getFund().getIsin());
});
Optional<FundBalance> activeFundBalance = fundBalances.stream()
.filter(fb -> fb.getFund().getName().equalsIgnoreCase(activeFundName))
.findFirst();
activeFundBalance.ifPresent( fb -> {
fb.setActiveContributions(true);
log.info("Setting active fund {}", fb.getFund().getName());
});
if(!activeFundBalance.isPresent()) {
log.info("Didn't find active fund {} from the list, creating one.", activeFundName);
fundBalances.add(constructActiveFundBalance(activeFundName));
}
return fundBalances;
}
private FundBalance constructActiveFundBalance(String activeFundName) {
FundBalance activeFundBalance = FundBalance.builder()
.value(BigDecimal.ZERO)
.currency("EUR")
.activeContributions(true)
.build();
Fund activeFund = fundRepository.findByNameIgnoreCase(activeFundName);
if (activeFund != null) {
activeFundBalance.setFund(activeFund);
} else {
log.error("Fund with name not found {}", activeFundName);
activeFundBalance.setFund(Fund.builder().name(activeFundName).build());
}
log.info("Constructed active fund for {} with isin {}",
activeFund.getName(), activeFund.getIsin());
return activeFundBalance;
}
}
| src/main/java/ee/tuleva/onboarding/account/AccountStatementService.java | package ee.tuleva.onboarding.account;
import ee.eesti.xtee6.kpr.PensionAccountBalanceResponseType;
import ee.eesti.xtee6.kpr.PensionAccountBalanceType;
import ee.eesti.xtee6.kpr.PersonalSelectionResponseType;
import ee.tuleva.onboarding.auth.principal.Person;
import ee.tuleva.onboarding.fund.Fund;
import ee.tuleva.onboarding.fund.FundRepository;
import ee.tuleva.onboarding.kpr.KPRClient;
import ee.tuleva.onboarding.mandate.statistics.FundValueStatistics;
import ee.tuleva.onboarding.mandate.statistics.FundValueStatisticsRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class AccountStatementService {
private final KPRClient kprClient;
private final FundRepository fundRepository;
private final KPRUnitsOsakudToFundBalanceConverter kprUnitsOsakudToFundBalanceConverter;
private final FundValueStatisticsRepository fundValueStatisticsRepository;
@Cacheable(value="balances", key="#person.personalCode.CASE_INSENSITIVE_ORDER")
public List<FundBalance> getMyPensionAccountStatement(Person person, UUID statisticsIdentifier) {
log.info("Getting pension account statement for {} {}", person.getFirstName(), person.getLastName());
List<FundBalance> fundBalances = convertXRoadResponse(getPensionAccountBalance(person));
fundBalances = handleActiveFundBalance(fundBalances, getActiveFundName(person));
saveFundValueStatistics(fundBalances, statisticsIdentifier);
return fundBalances;
}
private void saveFundValueStatistics(List<FundBalance> fundBalances, UUID fundValueStatisticsIdentifier) {
fundBalances.stream().map( fundBalance -> FundValueStatistics.builder()
.isin(fundBalance.getFund().getIsin())
.value(fundBalance.getValue())
.identifier(fundValueStatisticsIdentifier)
.build())
.forEach(fundValueStatisticsRepository::save);
}
private PensionAccountBalanceResponseType getPensionAccountBalance(Person person) {
PensionAccountBalanceType request = new PensionAccountBalanceType();
request.setBalanceDate(null);
return kprClient.pensionAccountBalance(request, person.getPersonalCode());
}
private List<FundBalance> convertXRoadResponse(PensionAccountBalanceResponseType response) {
return
response.getUnits().getBalance().stream()
.map(kprUnitsOsakudToFundBalanceConverter::convert)
.collect(Collectors.toList());
}
private String getActiveFundName(Person person) {
PersonalSelectionResponseType csdPersonalSelection = kprClient.personalSelection(person.getPersonalCode());
String activeFundName = csdPersonalSelection.getPensionAccount().getSecurityName();
log.info("Active fund name is {}", activeFundName);
return activeFundName;
}
private List<FundBalance> handleActiveFundBalance(List<FundBalance> fundBalances, String activeFundName) {
fundBalances.stream().forEach( fb-> {
log.info("Having fund {} with isin {}",
fb.getFund().getName(), fb.getFund().getIsin());
});
Optional<FundBalance> activeFundBalance = fundBalances.stream()
.filter(fb -> fb.getFund().getName().equalsIgnoreCase(activeFundName))
.findFirst();
activeFundBalance.ifPresent( fb -> {
fb.setActiveContributions(true);
log.info("Setting active fund {}", fb.getFund().getName());
});
if(!activeFundBalance.isPresent()) {
log.info("Didn't find active fund {} from the list, creating one.", activeFundName);
fundBalances.add(constructActiveFundBalance(activeFundName));
}
return fundBalances;
}
private FundBalance constructActiveFundBalance(String activeFundName) {
FundBalance activeFundBalance = FundBalance.builder()
.value(BigDecimal.ZERO)
.currency("EUR")
.activeContributions(true)
.build();
Fund activeFund = fundRepository.findByNameIgnoreCase(activeFundName);
if (activeFund != null) {
activeFundBalance.setFund(activeFund);
} else {
log.error("Fund with name not found {}", activeFundName);
activeFundBalance.setFund(Fund.builder().name(activeFundName).build());
}
log.info("Constructed active fund for {} with isin {}",
activeFund.getName(), activeFund.getIsin());
return activeFundBalance;
}
}
| Hotfixing master
| src/main/java/ee/tuleva/onboarding/account/AccountStatementService.java | Hotfixing master | <ide><path>rc/main/java/ee/tuleva/onboarding/account/AccountStatementService.java
<ide> import ee.tuleva.onboarding.mandate.statistics.FundValueStatisticsRepository;
<ide> import lombok.RequiredArgsConstructor;
<ide> import lombok.extern.slf4j.Slf4j;
<del>import org.springframework.cache.annotation.Cacheable;
<ide> import org.springframework.stereotype.Service;
<ide>
<ide> import java.math.BigDecimal;
<ide> private final KPRUnitsOsakudToFundBalanceConverter kprUnitsOsakudToFundBalanceConverter;
<ide> private final FundValueStatisticsRepository fundValueStatisticsRepository;
<ide>
<del> @Cacheable(value="balances", key="#person.personalCode.CASE_INSENSITIVE_ORDER")
<add>// @Cacheable(value="balances", key="#person.personalCode.CASE_INSENSITIVE_ORDER")
<ide> public List<FundBalance> getMyPensionAccountStatement(Person person, UUID statisticsIdentifier) {
<ide> log.info("Getting pension account statement for {} {}", person.getFirstName(), person.getLastName());
<ide> List<FundBalance> fundBalances = convertXRoadResponse(getPensionAccountBalance(person)); |
|
Java | apache-2.0 | 864e1f05efcabe573b45f8f27fd3c9fe8fca4d78 | 0 | rsby/gunmetal,gunmetal/gunmetal | /*
* Copyright (c) 2013.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gunmetal.internal;
import io.gunmetal.BlackList;
import io.gunmetal.Module;
import io.gunmetal.WhiteList;
import io.gunmetal.spi.ComponentMetadata;
import io.gunmetal.spi.ComponentMetadataResolver;
import io.gunmetal.spi.Dependency;
import io.gunmetal.spi.DependencyRequest;
import io.gunmetal.spi.ModuleMetadata;
import io.gunmetal.spi.ProvisionStrategy;
import io.gunmetal.spi.Qualifier;
import io.gunmetal.spi.QualifierResolver;
import io.gunmetal.spi.Scopes;
import io.gunmetal.spi.TypeKey;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* @author rees.byars
*/
class HandlerFactoryImpl implements HandlerFactory {
private final ComponentAdapterFactory componentAdapterFactory;
private final QualifierResolver qualifierResolver;
private final ComponentMetadataResolver componentMetadataResolver;
private final boolean requireExplicitModuleDependencies;
HandlerFactoryImpl(ComponentAdapterFactory componentAdapterFactory,
QualifierResolver qualifierResolver,
ComponentMetadataResolver componentMetadataResolver,
boolean requireExplicitModuleDependencies) {
this.componentAdapterFactory = componentAdapterFactory;
this.qualifierResolver = qualifierResolver;
this.componentMetadataResolver = componentMetadataResolver;
this.requireExplicitModuleDependencies = requireExplicitModuleDependencies;
}
@Override public List<DependencyRequestHandler<?>> createHandlersForModule(final Class<?> module,
GraphContext context,
Set<Class<?>> loadedModules) {
if (loadedModules.contains(module)) {
return Collections.emptyList();
}
loadedModules.add(module);
final Module moduleAnnotation = module.getAnnotation(Module.class);
if (moduleAnnotation == null) {
context.errors().add("The module class [" + module.getName()
+ "] must be annotated with @Module()");
return Collections.emptyList();
}
final RequestVisitor moduleRequestVisitor = moduleRequestVisitor(module, moduleAnnotation, context);
final ModuleMetadata moduleMetadata = moduleMetadata(module, moduleAnnotation, context);
final List<DependencyRequestHandler<?>> requestHandlers = new ArrayList<>();
addRequestHandlers(
moduleAnnotation,
module,
requestHandlers,
moduleMetadata,
moduleRequestVisitor,
context,
loadedModules);
return requestHandlers;
}
@Override public <T> DependencyRequestHandler<T> attemptToCreateHandlerFor(
final DependencyRequest<T> dependencyRequest, GraphContext context) {
final Dependency<T> dependency = dependencyRequest.dependency();
final TypeKey<T> typeKey = dependency.typeKey();
if (!isInstantiable(typeKey.raw())) {
return null;
}
final Class<? super T> cls = typeKey.raw();
final ModuleMetadata moduleMetadata = dependencyRequest.sourceModule(); // essentially, same as library
ComponentAdapter<T> componentAdapter = componentAdapterFactory.withClassProvider(
componentMetadataResolver.resolveMetadata(cls, moduleMetadata, context.errors()), context);
if (!componentAdapter.metadata().qualifier().equals(dependency.qualifier())) {
return null;
}
return requestHandler(
componentAdapter,
Collections.<Dependency<? super T>>singletonList(dependency),
RequestVisitor.NONE,
decorateForModule(moduleMetadata, AccessFilter.create(cls)),
context);
}
private RequestVisitor moduleRequestVisitor(final Class<?> module,
final Module moduleAnnotation,
GraphContext context) {
final RequestVisitor blackListVisitor = blackListVisitor(module, moduleAnnotation, context);
final RequestVisitor whiteListVisitor = whiteListVisitor(module, moduleAnnotation, context);
final RequestVisitor dependsOnVisitor = dependsOnVisitor(module);
final AccessFilter<Class<?>> classAccessFilter = AccessFilter.create(moduleAnnotation.access(), module);
final RequestVisitor moduleClassVisitor = (dependencyRequest, response) -> {
if (!classAccessFilter.isAccessibleTo(dependencyRequest.sourceModule().moduleClass())) {
response.addError(
"The module [" + dependencyRequest.sourceModule().moduleClass().getName()
+ "] does not have access to [" + classAccessFilter.filteredElement() + "]"
);
}
};
return (dependencyRequest, response) -> {
moduleClassVisitor.visit(dependencyRequest, response);
dependsOnVisitor.visit(dependencyRequest, response);
blackListVisitor.visit(dependencyRequest, response);
whiteListVisitor.visit(dependencyRequest, response);
};
}
private ModuleMetadata moduleMetadata(final Class<?> module, final Module moduleAnnotation, GraphContext context) {
final Qualifier qualifier = qualifierResolver.resolve(module, context.errors());
return new ModuleMetadata(module, qualifier, moduleAnnotation.dependsOn());
}
private RequestVisitor blackListVisitor(final Class<?> module, Module moduleAnnotation, GraphContext context) {
Class<? extends BlackList> blackListConfigClass =
moduleAnnotation.notAccessibleFrom();
if (blackListConfigClass == BlackList.class) {
return RequestVisitor.NONE;
}
final Class<?>[] blackListClasses;
BlackList.Modules blackListModules =
blackListConfigClass.getAnnotation(BlackList.Modules.class);
if (blackListModules != null) {
blackListClasses = blackListModules.value();
} else {
blackListClasses = new Class<?>[]{};
}
final Qualifier blackListQualifier = qualifierResolver.resolve(blackListConfigClass, context.errors());
return (dependencyRequest, response) -> {
Class<?> requestingSourceModuleClass = dependencyRequest.sourceModule().moduleClass();
for (Class<?> blackListClass : blackListClasses) {
if (blackListClass == requestingSourceModuleClass) {
response.addError("The module [" + requestingSourceModuleClass.getName()
+ "] does not have access to the module [" + module.getName() + "].");
}
}
boolean qualifierMatch =
blackListQualifier.qualifiers().length > 0
&& dependencyRequest.sourceQualifier().qualifiers().length > 0
&& dependencyRequest.sourceQualifier().intersects(blackListQualifier);
if (qualifierMatch) {
response.addError("The module [" + requestingSourceModuleClass.getName()
+ "] does not have access to the module [" + module.getName() + "].");
}
};
}
private RequestVisitor whiteListVisitor(final Class<?> module, Module moduleAnnotation, GraphContext context) {
Class<? extends WhiteList> whiteListConfigClass =
moduleAnnotation.onlyAccessibleFrom();
if (whiteListConfigClass == WhiteList.class) {
return RequestVisitor.NONE;
}
final Class<?>[] whiteListClasses;
WhiteList.Modules whiteListModules =
whiteListConfigClass.getAnnotation(WhiteList.Modules.class);
if (whiteListModules != null) {
whiteListClasses = whiteListModules.value();
} else {
whiteListClasses = new Class<?>[]{};
}
final Qualifier whiteListQualifier = qualifierResolver.resolve(whiteListConfigClass, context.errors());
return (dependencyRequest, response) -> {
Class<?> requestingSourceModuleClass = dependencyRequest.sourceModule().moduleClass();
for (Class<?> whiteListClass : whiteListClasses) {
if (whiteListClass == requestingSourceModuleClass) {
return;
}
}
boolean qualifierMatch = dependencyRequest.sourceQualifier().intersects(whiteListQualifier);
if (!qualifierMatch) {
response.addError("The module [" + requestingSourceModuleClass.getName()
+ "] does not have access to the module [" + module.getName() + "].");
}
};
}
private RequestVisitor dependsOnVisitor(final Class<?> module) {
return (dependencyRequest, response) -> {
ModuleMetadata requestSourceModule = dependencyRequest.sourceModule();
if (module == requestSourceModule.moduleClass()) {
return;
}
if (requestSourceModule.referencedModules().length == 0 && !requireExplicitModuleDependencies) {
return;
}
for (Class<?> dependency : requestSourceModule.referencedModules()) {
if (module == dependency) {
return;
}
}
response.addError("The module [" + requestSourceModule.moduleClass().getName()
+ "] does not have access to the module [" + module.getName() + "].");
};
}
private void addRequestHandlers(Module moduleAnnotation,
Class<?> module,
List<DependencyRequestHandler<?>> requestHandlers,
ModuleMetadata moduleMetadata,
RequestVisitor moduleRequestVisitor,
GraphContext context,
Set<Class<?>> loadedModules) {
if (moduleAnnotation.stateful()) {
if (!moduleAnnotation.provided()) {
requestHandlers.add(managedModuleRequestHandler(module, moduleMetadata, context));
} else {
requestHandlers.add(providedModuleRequestHandler(module, moduleMetadata, context));
}
Arrays.stream(module.getDeclaredMethods()).filter(m -> !m.isSynthetic()).forEach(m -> {
requestHandlers.add(statefulRequestHandler(m, module, moduleRequestVisitor, moduleMetadata, context));
});
} else {
Arrays.stream(module.getDeclaredMethods()).filter(m -> !m.isSynthetic()).forEach(m -> {
requestHandlers.add(requestHandler(m, module, moduleRequestVisitor, moduleMetadata, context));
});
}
for (Class<?> library : moduleAnnotation.subsumes()) {
Module libModule = library.getAnnotation(Module.class);
// TODO allow provided? require prototype?
Qualifier libQualifier = qualifierResolver.resolve(library, context.errors());
if (libModule == null) {
context.errors().add("A class without @Module cannot be subsumed");
} else if (!libModule.lib()) {
context.errors().add("@Module.lib must be true to be subsumed");
} else if (libQualifier != Qualifier.NONE) {
context.errors().add("Library " + library.getName() + " should not have a qualifier -> " + libQualifier);
}
addRequestHandlers(
libModule,
library,
requestHandlers,
moduleMetadata,
moduleRequestVisitor,
context,
loadedModules);
}
for (Class<?> m : moduleAnnotation.dependsOn()) {
requestHandlers.addAll(createHandlersForModule(m, context, loadedModules));
}
}
private AccessFilter<Class<?>> decorateForModule(ModuleMetadata moduleMetadata,
AccessFilter<Class<?>> accessFilter) {
return new AccessFilter<Class<?>>() {
@Override public AnnotatedElement filteredElement() {
return accessFilter.filteredElement();
}
@Override public boolean isAccessibleTo(Class<?> target) {
// supports library access
return target == moduleMetadata.moduleClass() || accessFilter.isAccessibleTo(target);
}
};
}
private <T> DependencyRequestHandler<T> requestHandler(
final Method method,
Class<?> module,
final RequestVisitor moduleRequestVisitor,
final ModuleMetadata moduleMetadata,
GraphContext context) {
int modifiers = method.getModifiers();
if (!Modifier.isStatic(modifiers)) {
throw new IllegalArgumentException("A module's provider methods must be static. The method ["
+ method.getName() + "] in module [" + module.getName() + "] is not static.");
}
if (method.getReturnType() == void.class) {
throw new IllegalArgumentException("A module's provider methods cannot have a void return type. The method ["
+ method.getName() + "] in module [" + module.getName() + "] is returns void.");
}
ComponentMetadata<Method> componentMetadata =
componentMetadataResolver.resolveMetadata(method, moduleMetadata, context.errors());
// TODO targeted return type check
final List<Dependency<? super T>> dependencies = Collections.<Dependency<? super T>>singletonList(
Dependency.from(componentMetadata.qualifier(), method.getGenericReturnType()));
return requestHandler(
componentAdapterFactory.<T>withMethodProvider(componentMetadata, context),
dependencies,
moduleRequestVisitor,
decorateForModule(moduleMetadata, AccessFilter.create(method)),
context);
}
private <T> DependencyRequestHandler<T> managedModuleRequestHandler(Class<T> module,
ModuleMetadata moduleMetadata,
GraphContext context) {
Dependency<T> dependency = Dependency.from(moduleMetadata.qualifier(), module);
ComponentAdapter<T> componentAdapter = componentAdapterFactory.withClassProvider(
componentMetadataResolver.resolveMetadata(module, moduleMetadata, context.errors()), context);
return requestHandler(
componentAdapter,
Collections.<Dependency<? super T>>singletonList(dependency),
(dependencyRequest, dependencyResponse) -> {
if (!dependencyRequest.sourceModule().equals(moduleMetadata)) {
dependencyResponse.addError("Module can only be requested by its providers"); // TODO
}
},
decorateForModule(moduleMetadata, AccessFilter.create(module)),
context);
}
private <T> DependencyRequestHandler<T> providedModuleRequestHandler(Class<T> module,
ModuleMetadata moduleMetadata,
GraphContext context) {
Dependency<T> dependency = Dependency.from(moduleMetadata.qualifier(), module);
ComponentMetadata<Class<?>> componentMetadata =
componentMetadataResolver.resolveMetadata(module, moduleMetadata, context.errors());
if (componentMetadata.scope() != Scopes.SINGLETON) {
context.errors().add(componentMetadata, "Provided modules must have a scope of singleton");
}
ComponentAdapter<T> componentAdapter = componentAdapterFactory.withProvidedModule(
componentMetadata, context);
return requestHandler(
componentAdapter,
Collections.<Dependency<? super T>>singletonList(dependency),
(dependencyRequest, dependencyResponse) -> {
if (!dependencyRequest.sourceModule().equals(moduleMetadata)) {
dependencyResponse.addError("Module can only be requested by its providers"); // TODO
}
},
decorateForModule(moduleMetadata, AccessFilter.create(module)),
context);
}
private <T> DependencyRequestHandler<T> statefulRequestHandler(
final Method method,
Class<?> module,
final RequestVisitor moduleRequestVisitor,
final ModuleMetadata moduleMetadata,
GraphContext context) {
int modifiers = method.getModifiers();
if (Modifier.isStatic(modifiers)) {
throw new IllegalArgumentException("A stateful module's provider methods must not be static. The method ["
+ method.getName() + "] in module [" + module.getName() + "] is static.");
}
if (method.getReturnType() == void.class) {
throw new IllegalArgumentException("A module's provider methods cannot have a void return type. The method ["
+ method.getName() + "] in module [" + module.getName() + "] is returns void.");
}
ComponentMetadata<Method> componentMetadata =
componentMetadataResolver.resolveMetadata(method, moduleMetadata, context.errors());
Dependency<T> componentDependency =
Dependency.from(componentMetadata.qualifier(), method.getGenericReturnType());
Dependency<?> moduleDependency =
Dependency.from(moduleMetadata.qualifier(), module);
// TODO targeted return type check
final List<Dependency<? super T>> dependencies =
Collections.<Dependency<? super T>>singletonList(componentDependency);
return requestHandler(
componentAdapterFactory.<T>withStatefulMethodProvider(componentMetadata, moduleDependency, context),
dependencies,
moduleRequestVisitor,
decorateForModule(moduleMetadata, AccessFilter.create(method)),
context);
}
private <T> DependencyRequestHandler<T> requestHandler(
final ComponentAdapter<T> componentAdapter,
final List<Dependency<? super T>> targets,
final RequestVisitor moduleRequestVisitor,
final AccessFilter<Class<?>> classAccessFilter,
GraphContext context) {
RequestVisitor scopeVisitor = (dependencyRequest, response) -> {
if (!componentAdapter.metadata().scope().canInject(dependencyRequest.sourceScope())) {
response.addError("mis-scoped"); // TODO message
}
};
return new DependencyRequestHandler<T>() {
@Override public List<Dependency<? super T>> targets() {
return targets;
}
@Override public List<Dependency<?>> dependencies() {
return componentAdapter.dependencies();
}
@Override public DependencyResponse<T> handle(DependencyRequest<? super T> dependencyRequest) {
MutableDependencyResponse<T> response =
new DependencyResponseImpl<>(dependencyRequest, componentAdapter.provisionStrategy(), context);
moduleRequestVisitor.visit(dependencyRequest, response);
scopeVisitor.visit(dependencyRequest, response);
if (!classAccessFilter.isAccessibleTo(dependencyRequest.sourceModule().moduleClass())) {
response.addError(
"The class [" + dependencyRequest.sourceOrigin().getName()
+ "] does not have access to [" + classAccessFilter.filteredElement() + "]"
);
}
return response;
}
@Override public ProvisionStrategy<T> force() {
return componentAdapter.provisionStrategy();
}
@Override public ComponentMetadata<?> componentMetadata() {
return componentAdapter.metadata();
}
@Override public DependencyRequestHandler<T> replicateWith(GraphContext context) {
return requestHandler(
componentAdapter.replicateWith(context),
targets,
moduleRequestVisitor,
classAccessFilter,
context);
}
};
}
private boolean isInstantiable(Class<?> cls) {
if (cls.isInterface()
|| cls.isArray()
|| cls.isEnum()
|| cls.isPrimitive()
|| cls.isSynthetic()
|| cls.isAnnotation()) {
return false;
}
int modifiers = cls.getModifiers();
return !Modifier.isAbstract(modifiers);
}
private interface MutableDependencyResponse<T> extends DependencyResponse<T> {
void addError(String errorMessage);
}
private interface RequestVisitor {
RequestVisitor NONE = (dependencyRequest, dependencyResponse) -> { };
void visit(DependencyRequest<?> dependencyRequest, MutableDependencyResponse<?> dependencyResponse);
}
private static class DependencyResponseImpl<T> implements MutableDependencyResponse<T> {
List<String> errors;
final DependencyRequest<? super T> dependencyRequest;
final ProvisionStrategy<? extends T> provisionStrategy;
final GraphContext context;
DependencyResponseImpl(DependencyRequest<? super T> dependencyRequest,
ProvisionStrategy<T> provisionStrategy,
GraphContext context) {
this.dependencyRequest = dependencyRequest;
this.provisionStrategy = provisionStrategy;
this.context = context;
}
@Override public void addError(String errorMessage) {
if (errors == null) {
errors = new LinkedList<>();
}
errors.add(errorMessage);
}
@Override public ValidatedDependencyResponse<T> validateResponse() {
if (errors != null) {
for (String error : errors) {
context.errors().add(
dependencyRequest.sourceComponent(),
"Denied request for " + dependencyRequest.dependency() + ". Reason -> " + error);
}
}
return new ValidatedDependencyResponse<T>() {
@Override public ProvisionStrategy<? extends T> getProvisionStrategy() {
return provisionStrategy;
}
@Override public ValidatedDependencyResponse<T> validateResponse() {
return this;
}
};
}
}
}
| core/src/main/java/io/gunmetal/internal/HandlerFactoryImpl.java | /*
* Copyright (c) 2013.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gunmetal.internal;
import io.gunmetal.BlackList;
import io.gunmetal.Module;
import io.gunmetal.WhiteList;
import io.gunmetal.spi.ComponentMetadata;
import io.gunmetal.spi.ComponentMetadataResolver;
import io.gunmetal.spi.Dependency;
import io.gunmetal.spi.DependencyRequest;
import io.gunmetal.spi.ModuleMetadata;
import io.gunmetal.spi.ProvisionStrategy;
import io.gunmetal.spi.Qualifier;
import io.gunmetal.spi.QualifierResolver;
import io.gunmetal.spi.Scopes;
import io.gunmetal.spi.TypeKey;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* @author rees.byars
*/
class HandlerFactoryImpl implements HandlerFactory {
private final ComponentAdapterFactory componentAdapterFactory;
private final QualifierResolver qualifierResolver;
private final ComponentMetadataResolver componentMetadataResolver;
private final boolean requireExplicitModuleDependencies;
HandlerFactoryImpl(ComponentAdapterFactory componentAdapterFactory,
QualifierResolver qualifierResolver,
ComponentMetadataResolver componentMetadataResolver,
boolean requireExplicitModuleDependencies) {
this.componentAdapterFactory = componentAdapterFactory;
this.qualifierResolver = qualifierResolver;
this.componentMetadataResolver = componentMetadataResolver;
this.requireExplicitModuleDependencies = requireExplicitModuleDependencies;
}
@Override public List<DependencyRequestHandler<?>> createHandlersForModule(final Class<?> module,
GraphContext context,
Set<Class<?>> loadedModules) {
if (loadedModules.contains(module)) {
return Collections.emptyList();
}
loadedModules.add(module);
final Module moduleAnnotation = module.getAnnotation(Module.class);
if (moduleAnnotation == null) {
context.errors().add("The module class [" + module.getName()
+ "] must be annotated with @Module()");
return Collections.emptyList();
}
final RequestVisitor moduleRequestVisitor = moduleRequestVisitor(module, moduleAnnotation, context);
final ModuleMetadata moduleMetadata = moduleMetadata(module, moduleAnnotation, context);
final List<DependencyRequestHandler<?>> requestHandlers = new ArrayList<>();
addRequestHandlers(
moduleAnnotation,
module,
requestHandlers,
moduleMetadata,
moduleRequestVisitor,
context,
loadedModules);
return requestHandlers;
}
@Override public <T> DependencyRequestHandler<T> attemptToCreateHandlerFor(
final DependencyRequest<T> dependencyRequest, GraphContext context) {
final Dependency<T> dependency = dependencyRequest.dependency();
final TypeKey<T> typeKey = dependency.typeKey();
if (!isInstantiable(typeKey.raw())) {
return null;
}
final Class<? super T> cls = typeKey.raw();
final ModuleMetadata moduleMetadata = dependencyRequest.sourceModule(); // essentially, same as library, okay?
ComponentAdapter<T> componentAdapter = componentAdapterFactory.withClassProvider(
componentMetadataResolver.resolveMetadata(cls, moduleMetadata, context.errors()), context);
if (!componentAdapter.metadata().qualifier().equals(dependency.qualifier())) {
return null;
}
return requestHandler(
componentAdapter,
Collections.<Dependency<? super T>>singletonList(dependency),
RequestVisitor.NONE,
AccessFilter.create(typeKey.raw()),
context);
}
private RequestVisitor moduleRequestVisitor(final Class<?> module,
final Module moduleAnnotation,
GraphContext context) {
final RequestVisitor blackListVisitor = blackListVisitor(module, moduleAnnotation, context);
final RequestVisitor whiteListVisitor = whiteListVisitor(module, moduleAnnotation, context);
final RequestVisitor dependsOnVisitor = dependsOnVisitor(module);
final AccessFilter<Class<?>> classAccessFilter = AccessFilter.create(moduleAnnotation.access(), module);
final RequestVisitor moduleClassVisitor = (dependencyRequest, response) -> {
if (!classAccessFilter.isAccessibleTo(dependencyRequest.sourceModule().moduleClass())) {
response.addError(
"The module [" + dependencyRequest.sourceModule().moduleClass().getName()
+ "] does not have access to [" + classAccessFilter.filteredElement() + "]"
);
}
};
return (dependencyRequest, response) -> {
moduleClassVisitor.visit(dependencyRequest, response);
dependsOnVisitor.visit(dependencyRequest, response);
blackListVisitor.visit(dependencyRequest, response);
whiteListVisitor.visit(dependencyRequest, response);
};
}
private ModuleMetadata moduleMetadata(final Class<?> module, final Module moduleAnnotation, GraphContext context) {
final Qualifier qualifier = qualifierResolver.resolve(module, context.errors());
return new ModuleMetadata(module, qualifier, moduleAnnotation.dependsOn());
}
private RequestVisitor blackListVisitor(final Class<?> module, Module moduleAnnotation, GraphContext context) {
Class<? extends BlackList> blackListConfigClass =
moduleAnnotation.notAccessibleFrom();
if (blackListConfigClass == BlackList.class) {
return RequestVisitor.NONE;
}
final Class<?>[] blackListClasses;
BlackList.Modules blackListModules =
blackListConfigClass.getAnnotation(BlackList.Modules.class);
if (blackListModules != null) {
blackListClasses = blackListModules.value();
} else {
blackListClasses = new Class<?>[]{};
}
final Qualifier blackListQualifier = qualifierResolver.resolve(blackListConfigClass, context.errors());
return (dependencyRequest, response) -> {
Class<?> requestingSourceModuleClass = dependencyRequest.sourceModule().moduleClass();
for (Class<?> blackListClass : blackListClasses) {
if (blackListClass == requestingSourceModuleClass) {
response.addError("The module [" + requestingSourceModuleClass.getName()
+ "] does not have access to the module [" + module.getName() + "].");
}
}
boolean qualifierMatch =
blackListQualifier.qualifiers().length > 0
&& dependencyRequest.sourceQualifier().qualifiers().length > 0
&& dependencyRequest.sourceQualifier().intersects(blackListQualifier);
if (qualifierMatch) {
response.addError("The module [" + requestingSourceModuleClass.getName()
+ "] does not have access to the module [" + module.getName() + "].");
}
};
}
private RequestVisitor whiteListVisitor(final Class<?> module, Module moduleAnnotation, GraphContext context) {
Class<? extends WhiteList> whiteListConfigClass =
moduleAnnotation.onlyAccessibleFrom();
if (whiteListConfigClass == WhiteList.class) {
return RequestVisitor.NONE;
}
final Class<?>[] whiteListClasses;
WhiteList.Modules whiteListModules =
whiteListConfigClass.getAnnotation(WhiteList.Modules.class);
if (whiteListModules != null) {
whiteListClasses = whiteListModules.value();
} else {
whiteListClasses = new Class<?>[]{};
}
final Qualifier whiteListQualifier = qualifierResolver.resolve(whiteListConfigClass, context.errors());
return (dependencyRequest, response) -> {
Class<?> requestingSourceModuleClass = dependencyRequest.sourceModule().moduleClass();
for (Class<?> whiteListClass : whiteListClasses) {
if (whiteListClass == requestingSourceModuleClass) {
return;
}
}
boolean qualifierMatch = dependencyRequest.sourceQualifier().intersects(whiteListQualifier);
if (!qualifierMatch) {
response.addError("The module [" + requestingSourceModuleClass.getName()
+ "] does not have access to the module [" + module.getName() + "].");
}
};
}
private RequestVisitor dependsOnVisitor(final Class<?> module) {
return (dependencyRequest, response) -> {
ModuleMetadata requestSourceModule = dependencyRequest.sourceModule();
if (module == requestSourceModule.moduleClass()) {
return;
}
if (requestSourceModule.referencedModules().length == 0 && !requireExplicitModuleDependencies) {
return;
}
for (Class<?> dependency : requestSourceModule.referencedModules()) {
if (module == dependency) {
return;
}
}
response.addError("The module [" + requestSourceModule.moduleClass().getName()
+ "] does not have access to the module [" + module.getName() + "].");
};
}
private void addRequestHandlers(Module moduleAnnotation,
Class<?> module,
List<DependencyRequestHandler<?>> requestHandlers,
ModuleMetadata moduleMetadata,
RequestVisitor moduleRequestVisitor,
GraphContext context,
Set<Class<?>> loadedModules) {
if (moduleAnnotation.stateful()) {
if (!moduleAnnotation.provided()) {
requestHandlers.add(managedModuleRequestHandler(module, moduleMetadata, context));
} else {
requestHandlers.add(providedModuleRequestHandler(module, moduleMetadata, context));
}
Arrays.stream(module.getDeclaredMethods()).filter(m -> !m.isSynthetic()).forEach(m -> {
requestHandlers.add(statefulRequestHandler(m, module, moduleRequestVisitor, moduleMetadata, context));
});
} else {
Arrays.stream(module.getDeclaredMethods()).filter(m -> !m.isSynthetic()).forEach(m -> {
requestHandlers.add(requestHandler(m, module, moduleRequestVisitor, moduleMetadata, context));
});
}
for (Class<?> library : moduleAnnotation.subsumes()) {
Module libModule = library.getAnnotation(Module.class);
// TODO allow provided? require prototype?
Qualifier libQualifier = qualifierResolver.resolve(library, context.errors());
if (libModule == null) {
context.errors().add("A class without @Module cannot be subsumed");
} else if (!libModule.lib()) {
context.errors().add("@Module.lib must be true to be subsumed");
} else if (libQualifier != Qualifier.NONE) {
context.errors().add("Library " + library.getName() + " should not have a qualifier -> " + libQualifier);
}
addRequestHandlers(
libModule,
library,
requestHandlers,
moduleMetadata,
moduleRequestVisitor,
context,
loadedModules);
}
for (Class<?> m : moduleAnnotation.dependsOn()) {
requestHandlers.addAll(createHandlersForModule(m, context, loadedModules));
}
}
private AccessFilter<Class<?>> decorateForModule(ModuleMetadata moduleMetadata,
AccessFilter<Class<?>> accessFilter) {
return new AccessFilter<Class<?>>() {
@Override public AnnotatedElement filteredElement() {
return accessFilter.filteredElement();
}
@Override public boolean isAccessibleTo(Class<?> target) {
// supports library access
return target == moduleMetadata.moduleClass() || accessFilter.isAccessibleTo(target);
}
};
}
private <T> DependencyRequestHandler<T> requestHandler(
final Method method,
Class<?> module,
final RequestVisitor moduleRequestVisitor,
final ModuleMetadata moduleMetadata,
GraphContext context) {
int modifiers = method.getModifiers();
if (!Modifier.isStatic(modifiers)) {
throw new IllegalArgumentException("A module's provider methods must be static. The method ["
+ method.getName() + "] in module [" + module.getName() + "] is not static.");
}
if (method.getReturnType() == void.class) {
throw new IllegalArgumentException("A module's provider methods cannot have a void return type. The method ["
+ method.getName() + "] in module [" + module.getName() + "] is returns void.");
}
ComponentMetadata<Method> componentMetadata =
componentMetadataResolver.resolveMetadata(method, moduleMetadata, context.errors());
// TODO targeted return type check
final List<Dependency<? super T>> dependencies = Collections.<Dependency<? super T>>singletonList(
Dependency.from(componentMetadata.qualifier(), method.getGenericReturnType()));
return requestHandler(
componentAdapterFactory.<T>withMethodProvider(componentMetadata, context),
dependencies,
moduleRequestVisitor,
decorateForModule(moduleMetadata, AccessFilter.create(method)),
context);
}
private <T> DependencyRequestHandler<T> managedModuleRequestHandler(Class<T> module,
ModuleMetadata moduleMetadata,
GraphContext context) {
Dependency<T> dependency = Dependency.from(moduleMetadata.qualifier(), module);
ComponentAdapter<T> componentAdapter = componentAdapterFactory.withClassProvider(
componentMetadataResolver.resolveMetadata(module, moduleMetadata, context.errors()), context);
return requestHandler(
componentAdapter,
Collections.<Dependency<? super T>>singletonList(dependency),
(dependencyRequest, dependencyResponse) -> {
if (!dependencyRequest.sourceModule().equals(moduleMetadata)) {
dependencyResponse.addError("Module can only be requested by its providers"); // TODO
}
},
decorateForModule(moduleMetadata, AccessFilter.create(module)),
context);
}
private <T> DependencyRequestHandler<T> providedModuleRequestHandler(Class<T> module,
ModuleMetadata moduleMetadata,
GraphContext context) {
Dependency<T> dependency = Dependency.from(moduleMetadata.qualifier(), module);
ComponentMetadata<Class<?>> componentMetadata =
componentMetadataResolver.resolveMetadata(module, moduleMetadata, context.errors());
if (componentMetadata.scope() != Scopes.SINGLETON) {
context.errors().add(componentMetadata, "Provided modules must have a scope of singleton");
}
ComponentAdapter<T> componentAdapter = componentAdapterFactory.withProvidedModule(
componentMetadata, context);
return requestHandler(
componentAdapter,
Collections.<Dependency<? super T>>singletonList(dependency),
(dependencyRequest, dependencyResponse) -> {
if (!dependencyRequest.sourceModule().equals(moduleMetadata)) {
dependencyResponse.addError("Module can only be requested by its providers"); // TODO
}
},
decorateForModule(moduleMetadata, AccessFilter.create(module)),
context);
}
private <T> DependencyRequestHandler<T> statefulRequestHandler(
final Method method,
Class<?> module,
final RequestVisitor moduleRequestVisitor,
final ModuleMetadata moduleMetadata,
GraphContext context) {
int modifiers = method.getModifiers();
if (Modifier.isStatic(modifiers)) {
throw new IllegalArgumentException("A stateful module's provider methods must not be static. The method ["
+ method.getName() + "] in module [" + module.getName() + "] is static.");
}
if (method.getReturnType() == void.class) {
throw new IllegalArgumentException("A module's provider methods cannot have a void return type. The method ["
+ method.getName() + "] in module [" + module.getName() + "] is returns void.");
}
ComponentMetadata<Method> componentMetadata =
componentMetadataResolver.resolveMetadata(method, moduleMetadata, context.errors());
Dependency<T> componentDependency =
Dependency.from(componentMetadata.qualifier(), method.getGenericReturnType());
Dependency<?> moduleDependency =
Dependency.from(moduleMetadata.qualifier(), module);
// TODO targeted return type check
final List<Dependency<? super T>> dependencies =
Collections.<Dependency<? super T>>singletonList(componentDependency);
return requestHandler(
componentAdapterFactory.<T>withStatefulMethodProvider(componentMetadata, moduleDependency, context),
dependencies,
moduleRequestVisitor,
decorateForModule(moduleMetadata, AccessFilter.create(method)),
context);
}
private <T> DependencyRequestHandler<T> requestHandler(
final ComponentAdapter<T> componentAdapter,
final List<Dependency<? super T>> targets,
final RequestVisitor moduleRequestVisitor,
final AccessFilter<Class<?>> classAccessFilter,
GraphContext context) {
RequestVisitor scopeVisitor = (dependencyRequest, response) -> {
if (!componentAdapter.metadata().scope().canInject(dependencyRequest.sourceScope())) {
response.addError("mis-scoped"); // TODO message
}
};
return new DependencyRequestHandler<T>() {
@Override public List<Dependency<? super T>> targets() {
return targets;
}
@Override public List<Dependency<?>> dependencies() {
return componentAdapter.dependencies();
}
@Override public DependencyResponse<T> handle(DependencyRequest<? super T> dependencyRequest) {
MutableDependencyResponse<T> response =
new DependencyResponseImpl<>(dependencyRequest, componentAdapter.provisionStrategy(), context);
moduleRequestVisitor.visit(dependencyRequest, response);
scopeVisitor.visit(dependencyRequest, response);
if (!classAccessFilter.isAccessibleTo(dependencyRequest.sourceModule().moduleClass())) {
response.addError(
"The class [" + dependencyRequest.sourceOrigin().getName()
+ "] does not have access to [" + classAccessFilter.filteredElement() + "]"
);
}
return response;
}
@Override public ProvisionStrategy<T> force() {
return componentAdapter.provisionStrategy();
}
@Override public ComponentMetadata<?> componentMetadata() {
return componentAdapter.metadata();
}
@Override public DependencyRequestHandler<T> replicateWith(GraphContext context) {
return requestHandler(
componentAdapter.replicateWith(context),
targets,
moduleRequestVisitor,
classAccessFilter,
context);
}
};
}
private boolean isInstantiable(Class<?> cls) {
if (cls.isInterface()
|| cls.isArray()
|| cls.isEnum()
|| cls.isPrimitive()
|| cls.isSynthetic()
|| cls.isAnnotation()) {
return false;
}
int modifiers = cls.getModifiers();
return !Modifier.isAbstract(modifiers);
}
private interface MutableDependencyResponse<T> extends DependencyResponse<T> {
void addError(String errorMessage);
}
private interface RequestVisitor {
RequestVisitor NONE = (dependencyRequest, dependencyResponse) -> { };
void visit(DependencyRequest<?> dependencyRequest, MutableDependencyResponse<?> dependencyResponse);
}
private static class DependencyResponseImpl<T> implements MutableDependencyResponse<T> {
List<String> errors;
final DependencyRequest<? super T> dependencyRequest;
final ProvisionStrategy<? extends T> provisionStrategy;
final GraphContext context;
DependencyResponseImpl(DependencyRequest<? super T> dependencyRequest,
ProvisionStrategy<T> provisionStrategy,
GraphContext context) {
this.dependencyRequest = dependencyRequest;
this.provisionStrategy = provisionStrategy;
this.context = context;
}
@Override public void addError(String errorMessage) {
if (errors == null) {
errors = new LinkedList<>();
}
errors.add(errorMessage);
}
@Override public ValidatedDependencyResponse<T> validateResponse() {
if (errors != null) {
for (String error : errors) {
context.errors().add(
dependencyRequest.sourceComponent(),
"Denied request for " + dependencyRequest.dependency() + ". Reason -> " + error);
}
}
return new ValidatedDependencyResponse<T>() {
@Override public ProvisionStrategy<? extends T> getProvisionStrategy() {
return provisionStrategy;
}
@Override public ValidatedDependencyResponse<T> validateResponse() {
return this;
}
};
}
}
}
| tweaking the auto-provided type handling to bring fully into line with library handling
| core/src/main/java/io/gunmetal/internal/HandlerFactoryImpl.java | tweaking the auto-provided type handling to bring fully into line with library handling | <ide><path>ore/src/main/java/io/gunmetal/internal/HandlerFactoryImpl.java
<ide> return null;
<ide> }
<ide> final Class<? super T> cls = typeKey.raw();
<del> final ModuleMetadata moduleMetadata = dependencyRequest.sourceModule(); // essentially, same as library, okay?
<add> final ModuleMetadata moduleMetadata = dependencyRequest.sourceModule(); // essentially, same as library
<ide> ComponentAdapter<T> componentAdapter = componentAdapterFactory.withClassProvider(
<ide> componentMetadataResolver.resolveMetadata(cls, moduleMetadata, context.errors()), context);
<ide> if (!componentAdapter.metadata().qualifier().equals(dependency.qualifier())) {
<ide> componentAdapter,
<ide> Collections.<Dependency<? super T>>singletonList(dependency),
<ide> RequestVisitor.NONE,
<del> AccessFilter.create(typeKey.raw()),
<add> decorateForModule(moduleMetadata, AccessFilter.create(cls)),
<ide> context);
<ide> }
<ide> |
|
Java | mpl-2.0 | d0b55f5f70e1badab0f4262a029851e1fab313c8 | 0 | codebu5ter/focus-android,Benestar/focus-android,Achintya999/focus-android,jonalmeida/focus-android,liuche/focus-android,mastizada/focus-android,mozilla-mobile/focus-android,layely/focus-android,liuche/focus-android,liuche/focus-android,Achintya999/focus-android,codebu5ter/focus-android,jonalmeida/focus-android,mastizada/focus-android,ekager/focus-android,pocmo/focus-android,liuche/focus-android,ekager/focus-android,Benestar/focus-android,layely/focus-android,mozilla-mobile/focus-android,jonalmeida/focus-android,codebu5ter/focus-android,liuche/focus-android,Benestar/focus-android,ekager/focus-android,Benestar/focus-android,mastizada/focus-android,mozilla-mobile/focus-android,jonalmeida/focus-android,mastizada/focus-android,ekager/focus-android,layely/focus-android,jonalmeida/focus-android,mozilla-mobile/focus-android,pocmo/focus-android,jonalmeida/focus-android,pocmo/focus-android,layely/focus-android,pocmo/focus-android,liuche/focus-android,pocmo/focus-android,pocmo/focus-android,Achintya999/focus-android,ekager/focus-android,mozilla-mobile/focus-android,codebu5ter/focus-android,layely/focus-android,Benestar/focus-android,ekager/focus-android,mastizada/focus-android,mozilla-mobile/focus-android,Achintya999/focus-android | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.activity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import org.mozilla.focus.R;
import org.mozilla.focus.fragment.BrowserFragment;
import org.mozilla.focus.fragment.FirstrunFragment;
import org.mozilla.focus.fragment.HomeFragment;
import org.mozilla.focus.utils.Settings;
import org.mozilla.focus.web.IWebView;
import org.mozilla.focus.web.WebViewProvider;
public class MainActivity extends AppCompatActivity {
private String pendingUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Settings appSettings = new Settings(this);
if (appSettings.shouldUseSecureMode()) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
}
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
setContentView(R.layout.activity_main);
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
final String url = getIntent().getDataString();
if (appSettings.shouldShowFirstrun()) {
pendingUrl = url;
showFirstrun();
} else {
showBrowserScreen(url);
}
} else {
if (appSettings.shouldShowFirstrun()) {
showFirstrun();
} else {
showHomeScreen();
}
}
WebViewProvider.preload(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
}
@Override
@SuppressLint("CommitTransaction")
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
// We can't update our fragment right now because we need to wait until the activity is
// resumed. So just remember this URL and load it in onResume().
pendingUrl = intent.getDataString();
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
if (pendingUrl != null && !new Settings(this).shouldShowFirstrun()) {
// We have received an URL in onNewIntent(). Let's load it now.
// Unless we're trying to show the firstrun screen, in which case we leave it pending until
// firstrun is dismissed.
showBrowserScreen(pendingUrl);
pendingUrl = null;
}
}
private void showHomeScreen() {
// We add the home fragment to the layout if it doesn't exist yet. I tried adding the fragment
// to the layout directly but then I wasn't able to remove it later. It was still visible but
// without an activity attached. So let's do it manually.
final FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentByTag(HomeFragment.FRAGMENT_TAG) == null) {
fragmentManager
.beginTransaction()
.replace(R.id.container, HomeFragment.create(), HomeFragment.FRAGMENT_TAG)
.commit();
}
}
private void showFirstrun() {
final FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentByTag(FirstrunFragment.FRAGMENT_TAG) == null) {
fragmentManager
.beginTransaction()
.replace(R.id.container, FirstrunFragment.create(), FirstrunFragment.FRAGMENT_TAG)
.commit();
}
}
private void showBrowserScreen(String url) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container,
BrowserFragment.create(url), BrowserFragment.FRAGMENT_TAG)
.commit();
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if (name.equals(IWebView.class.getName())) {
return WebViewProvider.create(this, attrs);
}
return super.onCreateView(name, context, attrs);
}
@Override
public void onBackPressed() {
final BrowserFragment browserFragment = (BrowserFragment) getSupportFragmentManager().findFragmentByTag(BrowserFragment.FRAGMENT_TAG);
if (browserFragment != null && browserFragment.isVisible() && browserFragment.canGoBack()) {
browserFragment.goBack();
return;
}
super.onBackPressed();
}
public void firstrunFinished() {
if (pendingUrl != null) {
// We have received an URL in onNewIntent(). Let's load it now.
showBrowserScreen(pendingUrl);
pendingUrl = null;
} else {
showHomeScreen();
}
}
}
| app/src/main/java/org/mozilla/focus/activity/MainActivity.java | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.activity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import org.mozilla.focus.R;
import org.mozilla.focus.fragment.BrowserFragment;
import org.mozilla.focus.fragment.FirstrunFragment;
import org.mozilla.focus.fragment.HomeFragment;
import org.mozilla.focus.utils.Settings;
import org.mozilla.focus.web.IWebView;
import org.mozilla.focus.web.WebViewProvider;
public class MainActivity extends AppCompatActivity {
private String pendingUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
setContentView(R.layout.activity_main);
final Settings appSettings = new Settings(this);
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
final String url = getIntent().getDataString();
if (appSettings.shouldShowFirstrun()) {
pendingUrl = url;
showFirstrun();
} else {
showBrowserScreen(url);
}
} else {
if (appSettings.shouldShowFirstrun()) {
showFirstrun();
} else {
showHomeScreen();
}
}
WebViewProvider.preload(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
if (appSettings.shouldUseSecureMode()) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
}
}
@Override
@SuppressLint("CommitTransaction")
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
// We can't update our fragment right now because we need to wait until the activity is
// resumed. So just remember this URL and load it in onResume().
pendingUrl = intent.getDataString();
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
if (pendingUrl != null && !new Settings(this).shouldShowFirstrun()) {
// We have received an URL in onNewIntent(). Let's load it now.
// Unless we're trying to show the firstrun screen, in which case we leave it pending until
// firstrun is dismissed.
showBrowserScreen(pendingUrl);
pendingUrl = null;
}
}
private void showHomeScreen() {
// We add the home fragment to the layout if it doesn't exist yet. I tried adding the fragment
// to the layout directly but then I wasn't able to remove it later. It was still visible but
// without an activity attached. So let's do it manually.
final FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentByTag(HomeFragment.FRAGMENT_TAG) == null) {
fragmentManager
.beginTransaction()
.replace(R.id.container, HomeFragment.create(), HomeFragment.FRAGMENT_TAG)
.commit();
}
}
private void showFirstrun() {
final FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentByTag(FirstrunFragment.FRAGMENT_TAG) == null) {
fragmentManager
.beginTransaction()
.replace(R.id.container, FirstrunFragment.create(), FirstrunFragment.FRAGMENT_TAG)
.commit();
}
}
private void showBrowserScreen(String url) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container,
BrowserFragment.create(url), BrowserFragment.FRAGMENT_TAG)
.commit();
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if (name.equals(IWebView.class.getName())) {
return WebViewProvider.create(this, attrs);
}
return super.onCreateView(name, context, attrs);
}
@Override
public void onBackPressed() {
final BrowserFragment browserFragment = (BrowserFragment) getSupportFragmentManager().findFragmentByTag(BrowserFragment.FRAGMENT_TAG);
if (browserFragment != null && browserFragment.isVisible() && browserFragment.canGoBack()) {
browserFragment.goBack();
return;
}
super.onBackPressed();
}
public void firstrunFinished() {
if (pendingUrl != null) {
// We have received an URL in onNewIntent(). Let's load it now.
showBrowserScreen(pendingUrl);
pendingUrl = null;
} else {
showHomeScreen();
}
}
}
| MainActivity: Call FLAG_SECURE early. (#325)
I can't reproduce #325 locally but we want to set the SECURE flag as early as
possible and not do a bunch of UI stuff first. Let's see if this might fix this.
| app/src/main/java/org/mozilla/focus/activity/MainActivity.java | MainActivity: Call FLAG_SECURE early. (#325) | <ide><path>pp/src/main/java/org/mozilla/focus/activity/MainActivity.java
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide>
<add> final Settings appSettings = new Settings(this);
<add>
<add> if (appSettings.shouldUseSecureMode()) {
<add> getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
<add> }
<add>
<ide> getWindow().getDecorView().setSystemUiVisibility(
<ide> View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
<ide>
<ide> setContentView(R.layout.activity_main);
<ide>
<del> final Settings appSettings = new Settings(this);
<ide> if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
<ide> final String url = getIntent().getDataString();
<ide>
<ide> WebViewProvider.preload(this);
<ide>
<ide> PreferenceManager.setDefaultValues(this, R.xml.settings, false);
<del>
<del> if (appSettings.shouldUseSecureMode()) {
<del> getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
<del> }
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | b856a44cefa24335333d79e1fb6c2b9e5fb72fd3 | 0 | adleritech/flexibee | package com.adleritech.flexibee.core.api.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IssuedInvoice {
@ElementList(name = "id", required = false, inline = true)
private List<String> id;
@Element(name = "typDokl", required = false)
private String documentType;
@Element(name = "stavUhrK", required = false)
private PaymentStatus paymentStatus;
@Element(name = "firma", required = false)
private String company;
@Element(name = "ic", required = false)
private String regNo;
@Element(name = "datVyst", required = false)
private LocalDate issued;
@Element(name = "datSplat", required = false)
private LocalDate dueDate;
@Element(name = "formaUhrK", required = false)
private PaymentMethod paymentMethod;
@Element(name = "duzpPuv", required = false)
private LocalDate timeOfSupply;
@Element(name = "bezPolozek", required = false)
private Boolean withoutItems;
@Element(name = "sumDphZakl", required = false)
private BigDecimal sumWithoutVat;
@Element(name = "zakazka", required = false)
private String order;
@Element(name = "formaUhradyCis", required = false)
private String paymentForm;
@Element(name = "polozkyFaktury", required = false)
private IssuedInvoiceItems items;
@ElementList(name="odpocty-zaloh", required = false)
private List<Deposit> deposits;
@Element(name="zavTxt", required = false)
private String text;
@Element(name="varSym", required = false)
private String variableSymbol;
@Element(name="sumZklCelkem", required = false)
private BigDecimal baseTotalSum;
@Element(name="sumCelkZakl", required = false)
private BigDecimal sumTotalWithoutVat;
@Element(name="sumCelkem", required = false)
private BigDecimal sumTotal;
}
| flexibee-core/src/main/java/com/adleritech/flexibee/core/api/domain/IssuedInvoice.java | package com.adleritech.flexibee.core.api.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IssuedInvoice {
@Element(name = "id", required = false)
private String id;
@Element(name = "typDokl", required = false)
private String documentType;
@Element(name = "stavUhrK", required = false)
private PaymentStatus paymentStatus;
@Element(name = "firma", required = false)
private String company;
@Element(name = "ic", required = false)
private String regNo;
@Element(name = "datVyst", required = false)
private LocalDate issued;
@Element(name = "datSplat", required = false)
private LocalDate dueDate;
@Element(name = "formaUhrK", required = false)
private PaymentMethod paymentMethod;
@Element(name = "duzpPuv", required = false)
private LocalDate timeOfSupply;
@Element(name = "bezPolozek", required = false)
private Boolean withoutItems;
@Element(name = "sumDphZakl", required = false)
private BigDecimal sumWithoutVat;
@Element(name = "zakazka", required = false)
private String order;
@Element(name = "formaUhradyCis", required = false)
private String paymentForm;
@Element(name = "polozkyFaktury", required = false)
private IssuedInvoiceItems items;
@ElementList(name="odpocty-zaloh", required = false)
private List<Deposit> deposits;
@Element(name="zavTxt", required = false)
private String text;
@Element(name="varSym", required = false)
private String variableSymbol;
@Element(name="sumZklCelkem", required = false)
private BigDecimal baseTotalSum;
@Element(name="sumCelkZakl", required = false)
private BigDecimal sumTotalWithoutVat;
@Element(name="sumCelkem", required = false)
private BigDecimal sumTotal;
}
| Change issued invoice id to be inline list
| flexibee-core/src/main/java/com/adleritech/flexibee/core/api/domain/IssuedInvoice.java | Change issued invoice id to be inline list | <ide><path>lexibee-core/src/main/java/com/adleritech/flexibee/core/api/domain/IssuedInvoice.java
<ide> @NoArgsConstructor
<ide> @AllArgsConstructor
<ide> public class IssuedInvoice {
<del> @Element(name = "id", required = false)
<del> private String id;
<add> @ElementList(name = "id", required = false, inline = true)
<add> private List<String> id;
<ide>
<ide> @Element(name = "typDokl", required = false)
<ide> private String documentType; |
|
JavaScript | mit | 0e44ddce750c955c258a53be6a9604d37c38ead6 | 0 | rlugojr/melonJS,Smoss/Enoru-eco,MarkoIvanetic/melonJS,melonjs/melonJS,melonjs/melonJS,srbala/melonJS,gopalindians/melonJS,rlugojr/melonJS,TukekeSoft/melonJS,gopalindians/melonJS,TukekeSoft/melonJS,TukekeSoft/melonJS,gopalindians/melonJS,srbala/melonJS,Smoss/Enoru-eco,rlugojr/melonJS,srbala/melonJS,MarkoIvanetic/melonJS | /*
* MelonJS Game Engine
* Copyright (C) 2012, Olivier BIOT
* http://www.melonjs.org
*
*/
(function($) {
/**
* a Timer object to manage time function (FPS, Game Tick, Time...)<p>
* There is no constructor function for me.timer
* @final
* @memberOf me
* @constructor Should not be called by the user.
*/
me.timer = (function() {
// hold public stuff in our api
var api = {};
/*---------------------------------------------
PRIVATE STUFF
---------------------------------------------*/
//hold element to display fps
var htmlCounter = null;
var debug = false;
var framecount = 0;
var framedelta = 0;
/* fps count stuff */
var last = 0;
var now = 0;
var delta = 0;
var step = Math.ceil(1000 / me.sys.fps); // ROUND IT ?
// define some step with some margin
var minstep = (1000 / me.sys.fps) * 1.25; // IS IT NECESSARY?
/**
* draw the fps counter
* @private
*/
function draw(fps) {
htmlCounter.replaceChild(document.createTextNode("(" + fps + "/"
+ me.sys.fps + " fps)"), htmlCounter.firstChild);
};
/*---------------------------------------------
PUBLIC STUFF
---------------------------------------------*/
/**
* last game tick value
* @public
* @type {Int}
* @name me.timer#tick
*/
api.tick = 1.0;
/**
* last measured fps rate
* @public
* @type {Int}
* @name me.timer#fps
*/
api.fps = 0;
/* ---
init our time stuff
--- */
api.init = function() {
// check if we have a fps counter display in the HTML
htmlCounter = document.getElementById("framecounter");
if (htmlCounter !== null) {
me.debug.displayFPS = true;
}
// reset variables to initial state
api.reset();
};
/**
* reset time (e.g. usefull in case of pause)
* @name me.timer#reset
* @private
* @function
*/
api.reset = function() {
// set to "now"
now = last = Date.now();
// reset delta counting variables
framedelta = 0;
framecount = 0;
};
/**
* return the current time
* @name me.timer#getTime
* @return {Date}
* @function
*/
api.getTime = function() {
return now;
};
/* ---
update game tick
should be called once a frame
--- */
api.update = function() {
last = now;
now = Date.now();
delta = (now - last);
// only draw the FPS on in the HTML page
if (me.debug.displayFPS) {
framecount++;
framedelta += delta;
if (framecount % 10 == 0) {
this.fps = (~~((1000 * framecount) / framedelta)).clamp(0, me.sys.fps);
framedelta = 0;
framecount = 0;
}
// set the element in the HTML
if (htmlCounter !== null) {
draw(this.fps);
}
}
// get the game tick
api.tick = (delta > minstep && me.sys.interpolation) ? delta / step : 1;
};
// return our apiect
return api;
})();
/************************************************************************************/
/**
* video functions
* There is no constructor function for me.video
* @final
* @memberOf me
* @constructor Should not be called by the user.
*/
me.video = (function() {
// hold public stuff in our apig
var api = {};
// internal variables
var canvas = null;
var context2D = null;
var backBufferCanvas = null;
var backBufferContext2D = null;
var wrapper = null;
var deferResizeId = -1;
var double_buffering = false;
var game_width_zoom = 0;
var game_height_zoom = 0;
var auto_scale = false;
var maintainAspectRatio = true;
/*---------------------------------------------
PUBLIC STUFF
---------------------------------------------*/
/* ---
init the video part
--- */
/**
* init the "video" part<p>
* return false if initialization failed (canvas not supported)
* @name me.video#init
* @function
* @param {String} wrapper the "div" element id to hold the canvas in the HTML file (if null document.body will be used)
* @param {Int} width game width
* @param {Int} height game height
* @param {Boolean} [double_buffering] enable/disable double buffering
* @param {Number} [scale] enable scaling of the canvas ('auto' for automatic scaling)
* @param {Boolean} [maintainAspectRatio] maintainAspectRatio when scaling the display
* @return {Boolean}
* @example
* // init the video with a 480x320 canvas
* if (!me.video.init('jsapp', 480, 320))
* {
* alert("Sorry but your browser does not support html 5 canvas !");
* return;
* }
*/
api.init = function(wrapperid, game_width, game_height, doublebuffering, scale, aspectRatio) {
// ensure melonjs has been properly initialized
if (!me.initialized) {
throw "melonJS: me.video.init() called before engine initialization.";
}
// check given parameters
double_buffering = doublebuffering || false;
auto_scale = (scale==='auto') || false;
maintainAspectRatio = (aspectRatio !== undefined) ? aspectRatio : true;
// normalize scale
scale = (scale!=='auto') ? parseFloat(scale || 1.0) : 1.0
me.sys.scale = new me.Vector2d(scale, scale);
// force double buffering if scaling is required
if (auto_scale || (scale !== 1.0)) {
double_buffering = true;
}
// default scaled size value
game_width_zoom = game_width * me.sys.scale.x;
game_height_zoom = game_height * me.sys.scale.y;
//add a channel for the onresize/onorientationchange event
window.addEventListener('resize', function (event) {me.event.publish(me.event.WINDOW_ONRESIZE, [event])}, false);
window.addEventListener('orientationchange', function (event) {me.event.publish(me.event.WINDOW_ONRESIZE, [event])}, false);
// register to the channel
me.event.subscribe(me.event.WINDOW_ONRESIZE, me.video.onresize.bind(me.video));
// create the main canvas
canvas = document.createElement("canvas");
canvas.setAttribute("width", (game_width_zoom) + "px");
canvas.setAttribute("height", (game_height_zoom) + "px");
canvas.setAttribute("border", "0px solid black");
canvas.setAttribute("display", "block"); // ??
// add our canvas
if (wrapperid) {
wrapper = document.getElementById(wrapperid);
}
else {
// if wrapperid is not defined (null)
// add the canvas to document.body
wrapper = document.body;
}
wrapper.appendChild(canvas);
// stop here if not supported
if (!canvas.getContext)
return false;
// get the 2D context
context2D = canvas.getContext('2d');
// create the back buffer if we use double buffering
if (double_buffering) {
backBufferContext2D = api.createCanvasSurface(game_width, game_height);
backBufferCanvas = backBufferContext2D.canvas;
} else {
backBufferContext2D = context2D;
backBufferCanvas = context2D.canvas;
}
// trigger an initial resize();
if (auto_scale) {
me.video.onresize(null);
}
return true;
};
/**
* return a reference to the wrapper
* @name me.video#getWrapper
* @function
* @return {Document}
*/
api.getWrapper = function() {
return wrapper;
};
/**
* return the width of the display canvas (before scaling)
* @name me.video#getWidth
* @function
* @return {Int}
*/
api.getWidth = function() {
return backBufferCanvas.width;
};
/**
* return the relative (to the page) position of the specified Canvas
* @name me.video#getPos
* @function
* @param {Canvas} [canvas] system one if none specified
* @return {me.Vector2d}
*/
api.getPos = function(c) {
var obj = c || canvas;
var offset = new me.Vector2d(obj.offsetLeft, obj.offsetTop);
while ( obj = obj.offsetParent ) {
offset.x += obj.offsetLeft;
offset.y += obj.offsetTop;
}
return offset;
};
/**
* return the height of the display canvas (before scaling)
* @name me.video#getHeight
* @function
* @return {Int}
*/
api.getHeight = function() {
return backBufferCanvas.height;
};
/**
* allocate and return a new Canvas 2D surface
* @name me.video#createCanvasSurface
* @function
* @param {Int} width canvas width
* @param {Int} height canvas height
* @return {Context2D}
*/
api.createCanvasSurface = function(width, height) {
var privateCanvas = document.createElement("canvas");
privateCanvas.width = width || backBufferCanvas.width;
privateCanvas.height = height || backBufferCanvas.height;
return privateCanvas.getContext('2d');
};
/**
* return a reference of the display canvas
* @name me.video#getScreenCanvas
* @function
* @return {Canvas}
*/
api.getScreenCanvas = function() {
return canvas;
};
/**
* return a reference to the screen framebuffer
* @name me.video#getScreenFrameBuffer
* @function
* @return {Context2D}
*/
api.getScreenFrameBuffer = function() {
return backBufferContext2D;
};
/**
* callback for window resize event
* @private
*/
api.onresize = function(event){
if (auto_scale) {
// get the parent container max size
var parent = me.video.getScreenCanvas().parentNode;
var max_width = parent.width || window.innerWidth;
var max_height = parent.height || window.innerHeight;
if (deferResizeId) {
// cancel any previous pending resize
clearTimeout(deferResizeId);
}
if (maintainAspectRatio) {
// make sure we maintain the original aspect ratio
var designRatio = me.video.getWidth() / me.video.getHeight();
var screenRatio = max_width / max_height;
if (screenRatio < designRatio)
var scale = max_width / me.video.getWidth();
else
var scale = max_height / me.video.getHeight();
// update the "front" canvas size
deferResizeId = me.video.updateDisplaySize.defer(scale,scale);
} else {
// scale the display canvas to fit with the parent container
deferResizeId = me.video.updateDisplaySize.defer(
max_width / me.video.getWidth(),
max_height / me.video.getHeight()
);
}
return;
}
// make sure we have the correct relative canvas position cached
me.input.mouse.offset = me.video.getPos();
};
/**
* Modify the "displayed" canvas size
* @name me.video#updateDisplaySize
* @function
* @param {Number} scale X scaling value
* @param {Number} scale Y scaling value
*/
api.updateDisplaySize = function(scaleX, scaleY) {
// update the global scale variable
me.sys.scale.set(scaleX,scaleY);
// apply the new value
canvas.width = game_width_zoom = backBufferCanvas.width * scaleX;
canvas.height = game_height_zoom = backBufferCanvas.height * scaleY;
// make sure we have the correct relative canvas position cached
me.input.mouse.offset = me.video.getPos();
// force a canvas repaint
api.blitSurface();
// clear the timeout id
deferResizeId = -1;
};
/**
* Clear the specified context with the given color
* @name me.video#clearSurface
* @function
* @param {Context2D} context
* @param {Color} col
*/
api.clearSurface = function(context, col) {
context.save();
context.setTransform(1, 0, 0, 1, 0, 0);
context.fillStyle = col;
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
context.restore();
};
/**
* scale & keep canvas centered<p>
* usefull for zooming effect
* @name me.video#scale
* @function
* @param {Context2D} context
* @param {scale} scale
*/
api.scale = function(context, scale) {
context.translate(
-(((context.canvas.width * scale) - context.canvas.width) >> 1),
-(((context.canvas.height * scale) - context.canvas.height) >> 1));
context.scale(scale, scale);
};
/**
* enable/disable Alpha for the specified context
* @name me.video#setAlpha
* @function
* @param {Context2D} context
* @param {Boolean} enable
*/
api.setAlpha = function(context, enable) {
context.globalCompositeOperation = enable ? "source-over" : "copy";
};
/**
* render the main framebuffer on screen
* @name me.video#blitSurface
* @function
*/
api.blitSurface = function() {
if (double_buffering) {
api.blitSurface = function() {
//FPS.update();
context2D.drawImage(backBufferCanvas, 0, 0,
backBufferCanvas.width, backBufferCanvas.height, 0,
0, game_width_zoom, game_height_zoom);
};
} else {
// "empty" function, as we directly render stuff on "context2D"
api.blitSurface = function() {
};
}
api.blitSurface();
};
/**
* apply the specified filter to the main canvas
* and return a new canvas object with the modified output<br>
* (!) Due to the internal usage of getImageData to manipulate pixels,
* this function will throw a Security Exception with FF if used locally
* @name me.video#applyRGBFilter
* @function
* @param {Object} object Canvas or Image Object on which to apply the filter
* @param {String} effect "b&w", "brightness", "transparent"
* @param {String} option : level [0...1] (for brightness), color to be replaced (for transparent)
* @return {Context2D} context object
*/
api.applyRGBFilter = function(object, effect, option) {
//create a output canvas using the given canvas or image size
var fcanvas = api.createCanvasSurface(object.width, object.height);
// get the pixels array of the give parameter
var imgpix = me.utils.getPixels(object);
// pointer to the pixels data
var pix = imgpix.data;
// apply selected effect
switch (effect) {
case "b&w": {
for ( var i = 0, n = pix.length; i < n; i += 4) {
var grayscale = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) >>> 3;
pix[i] = grayscale; // red
pix[i + 1] = grayscale; // green
pix[i + 2] = grayscale; // blue
}
break;
}
case "brightness": {
// make sure it's between 0.0 and 1.0
var brightness = Math.abs(option).clamp(0.0, 1.0);
for ( var i = 0, n = pix.length; i < n; i += 4) {
pix[i] *= brightness; // red
pix[i + 1] *= brightness; // green
pix[i + 2] *= brightness; // blue
}
break;
}
case "transparent": {
for ( var i = 0, n = pix.length; i < n; i += 4) {
if (me.utils.RGBToHex(pix[i], pix[i + 1], pix[i + 2]) === option) {
pix[i + 3] = 0;
}
}
break;
}
default:
return null;
}
// put our modified image back in the new filtered canvas
fcanvas.putImageData(imgpix, 0, 0);
// return it
return fcanvas;
};
// return our api
return api;
})();
/*---------------------------------------------------------*/
// END END END
/*---------------------------------------------------------*/
})(window);
| src/video/video.js | /*
* MelonJS Game Engine
* Copyright (C) 2012, Olivier BIOT
* http://www.melonjs.org
*
*/
(function($) {
/**
* a Timer object to manage time function (FPS, Game Tick, Time...)<p>
* There is no constructor function for me.timer
* @final
* @memberOf me
* @constructor Should not be called by the user.
*/
me.timer = (function() {
// hold public stuff in our api
var api = {};
/*---------------------------------------------
PRIVATE STUFF
---------------------------------------------*/
//hold element to display fps
var htmlCounter = null;
var debug = false;
var framecount = 0;
var framedelta = 0;
/* fps count stuff */
var last = 0;
var now = 0;
var delta = 0;
var step = Math.ceil(1000 / me.sys.fps); // ROUND IT ?
// define some step with some margin
var minstep = (1000 / me.sys.fps) * 1.25; // IS IT NECESSARY?
/**
* draw the fps counter
* @private
*/
function draw(fps) {
htmlCounter.replaceChild(document.createTextNode("(" + fps + "/"
+ me.sys.fps + " fps)"), htmlCounter.firstChild);
};
/*---------------------------------------------
PUBLIC STUFF
---------------------------------------------*/
/**
* last game tick value
* @public
* @type {Int}
* @name me.timer#tick
*/
api.tick = 1.0;
/**
* last measured fps rate
* @public
* @type {Int}
* @name me.timer#fps
*/
api.fps = 0;
/* ---
init our time stuff
--- */
api.init = function() {
// check if we have a fps counter display in the HTML
htmlCounter = document.getElementById("framecounter");
if (htmlCounter !== null) {
me.debug.displayFPS = true;
}
// reset variables to initial state
api.reset();
};
/**
* reset time (e.g. usefull in case of pause)
* @name me.timer#reset
* @private
* @function
*/
api.reset = function() {
// set to "now"
now = last = Date.now();
// reset delta counting variables
framedelta = 0;
framecount = 0;
};
/**
* return the current time
* @name me.timer#getTime
* @return {Date}
* @function
*/
api.getTime = function() {
return now;
};
/* ---
update game tick
should be called once a frame
--- */
api.update = function() {
last = now;
now = Date.now();
delta = (now - last);
// only draw the FPS on in the HTML page
if (me.debug.displayFPS) {
framecount++;
framedelta += delta;
if (framecount % 10 == 0) {
this.fps = (~~((1000 * framecount) / framedelta)).clamp(0, me.sys.fps);
framedelta = 0;
framecount = 0;
}
// set the element in the HTML
if (htmlCounter !== null) {
draw(this.fps);
}
}
// get the game tick
api.tick = (delta > minstep && me.sys.interpolation) ? delta / step : 1;
};
// return our apiect
return api;
})();
/************************************************************************************/
/**
* video functions
* There is no constructor function for me.video
* @final
* @memberOf me
* @constructor Should not be called by the user.
*/
me.video = (function() {
// hold public stuff in our apig
var api = {};
// internal variables
var canvas = null;
var context2D = null;
var backBufferCanvas = null;
var backBufferContext2D = null;
var wrapper = null;
var deferResizeId = -1;
var double_buffering = false;
var game_width_zoom = 0;
var game_height_zoom = 0;
var auto_scale = false;
var maintainAspectRatio = true;
/*---------------------------------------------
PUBLIC STUFF
---------------------------------------------*/
/* ---
init the video part
--- */
/**
* init the "video" part<p>
* return false if initialization failed (canvas not supported)
* @name me.video#init
* @function
* @param {String} wrapper the "div" element id to hold the canvas in the HTML file (if null document.body will be used)
* @param {Int} width game width
* @param {Int} height game height
* @param {Boolean} [double_buffering] enable/disable double buffering
* @param {Number} [scale] enable scaling of the canvas ('auto' for automatic scaling)
* @param {Boolean} [maintainAspectRatio] maintainAspectRatio when scaling the display
* @return {Boolean}
* @example
* // init the video with a 480x320 canvas
* if (!me.video.init('jsapp', 480, 320))
* {
* alert("Sorry but your browser does not support html 5 canvas !");
* return;
* }
*/
api.init = function(wrapperid, game_width, game_height, doublebuffering, scale, aspectRatio) {
// ensure melonjs has been properly initialized
if (!me.initialized) {
throw "melonJS: me.video.init() called before engine initialization.";
}
// check given parameters
double_buffering = doublebuffering || false;
auto_scale = (scale==='auto') || false;
maintainAspectRatio = (aspectRatio !== undefined) ? aspectRatio : true;
// normalize scale
scale = (scale!=='auto') ? parseFloat(scale || 1.0) : 1.0
me.sys.scale = new me.Vector2d(scale, scale);
// force double buffering if scaling is required
if (auto_scale || (scale !== 1.0)) {
double_buffering = true;
}
// default scaled size value
game_width_zoom = game_width * me.sys.scale.x;
game_height_zoom = game_height * me.sys.scale.y;
//add a channel for the onresize/onorientationchange event
window.addEventListener('resize', function (event) {me.event.publish(me.event.WINDOW_ONRESIZE, [event])}, false);
window.addEventListener('orientationchange', function (event) {me.event.publish(me.event.WINDOW_ONRESIZE, [event])}, false);
// register to the channel
me.event.subscribe(me.event.WINDOW_ONRESIZE, me.video.onresize.bind(me.video));
// create the main canvas
canvas = document.createElement("canvas");
canvas.setAttribute("width", (game_width_zoom) + "px");
canvas.setAttribute("height", (game_height_zoom) + "px");
canvas.setAttribute("border", "0px solid black");
canvas.setAttribute("display", "block"); // ??
// add our canvas
if (wrapperid) {
wrapper = document.getElementById(wrapperid);
}
else {
// if wrapperid is not defined (null)
// add the canvas to document.body
wrapper = document.body;
}
wrapper.appendChild(canvas);
// stop here if not supported
if (!canvas.getContext)
return false;
// get the 2D context
context2D = canvas.getContext('2d');
// create the back buffer if we use double buffering
if (double_buffering) {
backBufferContext2D = api.createCanvasSurface(game_width, game_height);
backBufferCanvas = backBufferContext2D.canvas;
} else {
backBufferContext2D = context2D;
backBufferCanvas = context2D.canvas;
}
// trigger an initial resize();
if (auto_scale) {
me.video.onresize(null);
}
return true;
};
/**
* return a reference to the wrapper
* @name me.video#getWrapper
* @function
* @return {Document}
*/
api.getWrapper = function() {
return wrapper;
};
/**
* return the width of the display canvas (before scaling)
* @name me.video#getWidth
* @function
* @return {Int}
*/
api.getWidth = function() {
return backBufferCanvas.width;
};
/**
* return the relative (to the page) position of the specified Canvas
* @name me.video#getPos
* @function
* @param {Canvas} [canvas] system one if none specified
* @return {me.Vector2d}
*/
api.getPos = function(c) {
var obj = c || canvas;
var offset = new me.Vector2d(obj.offsetLeft, obj.offsetTop);
while ( obj = obj.offsetParent ) {
offset.x += obj.offsetLeft;
offset.y += obj.offsetTop;
}
return offset;
};
/**
* return the height of the display canvas (before scaling)
* @name me.video#getHeight
* @function
* @return {Int}
*/
api.getHeight = function() {
return backBufferCanvas.height;
};
/**
* allocate and return a new Canvas 2D surface
* @name me.video#createCanvasSurface
* @function
* @param {Int} width canvas width
* @param {Int} height canvas height
* @return {Context2D}
*/
api.createCanvasSurface = function(width, height) {
var privateCanvas = document.createElement("canvas");
privateCanvas.width = width || backBufferCanvas.width;
privateCanvas.height = height || backBufferCanvas.height;
return privateCanvas.getContext('2d');
};
/**
* return a reference of the display canvas
* @name me.video#getScreenCanvas
* @function
* @return {Canvas}
*/
api.getScreenCanvas = function() {
return canvas;
};
/**
* return a reference to the screen framebuffer
* @name me.video#getScreenFrameBuffer
* @function
* @return {Context2D}
*/
api.getScreenFrameBuffer = function() {
return backBufferContext2D;
};
/**
* callback for window resize event
* @private
*/
api.onresize = function(event){
if (auto_scale) {
// get the parent container max size
var parent = me.video.getScreenCanvas().parentNode;
var max_width = parent.width || window.innerWidth;
var max_height = parent.height || window.innerHeight;
if (deferResizeId) {
// cancel any previous pending resize
clearTimeout(deferResizeId);
}
if (maintainAspectRatio) {
// make sure we maintain the original aspect ratio
var designRatio = me.video.getWidth() / me.video.getHeight();
var screenRatio = max_width / max_height;
if (screenRatio < designRatio)
var scale = max_width / me.video.getWidth();
else
var scale = max_height / me.video.getHeight();
// update the "front" canvas size
deferResizeId = me.video.updateDisplaySize.defer(scale,scale);
} else {
// scale the display canvas to fit with the parent container
deferResizeId = me.video.updateDisplaySize.defer(
max_width / me.video.getWidth(),
max_height / me.video.getHeight()
);
}
}
// make sure we have the correct relative canvas position cached
me.input.mouse.offset = me.video.getPos();
};
/**
* Modify the "displayed" canvas size
* @name me.video#updateDisplaySize
* @function
* @param {Number} scale X scaling value
* @param {Number} scale Y scaling value
*/
api.updateDisplaySize = function(scaleX, scaleY) {
// update the global scale variable
me.sys.scale.set(scaleX,scaleY);
// apply the new value
canvas.width = game_width_zoom = backBufferCanvas.width * scaleX;
canvas.height = game_height_zoom = backBufferCanvas.height * scaleY;
// force a canvas repaint
api.blitSurface();
// clear the timeout id
deferResizeId = -1;
};
/**
* Clear the specified context with the given color
* @name me.video#clearSurface
* @function
* @param {Context2D} context
* @param {Color} col
*/
api.clearSurface = function(context, col) {
context.save();
context.setTransform(1, 0, 0, 1, 0, 0);
context.fillStyle = col;
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
context.restore();
};
/**
* scale & keep canvas centered<p>
* usefull for zooming effect
* @name me.video#scale
* @function
* @param {Context2D} context
* @param {scale} scale
*/
api.scale = function(context, scale) {
context.translate(
-(((context.canvas.width * scale) - context.canvas.width) >> 1),
-(((context.canvas.height * scale) - context.canvas.height) >> 1));
context.scale(scale, scale);
};
/**
* enable/disable Alpha for the specified context
* @name me.video#setAlpha
* @function
* @param {Context2D} context
* @param {Boolean} enable
*/
api.setAlpha = function(context, enable) {
context.globalCompositeOperation = enable ? "source-over" : "copy";
};
/**
* render the main framebuffer on screen
* @name me.video#blitSurface
* @function
*/
api.blitSurface = function() {
if (double_buffering) {
api.blitSurface = function() {
//FPS.update();
context2D.drawImage(backBufferCanvas, 0, 0,
backBufferCanvas.width, backBufferCanvas.height, 0,
0, game_width_zoom, game_height_zoom);
};
} else {
// "empty" function, as we directly render stuff on "context2D"
api.blitSurface = function() {
};
}
api.blitSurface();
};
/**
* apply the specified filter to the main canvas
* and return a new canvas object with the modified output<br>
* (!) Due to the internal usage of getImageData to manipulate pixels,
* this function will throw a Security Exception with FF if used locally
* @name me.video#applyRGBFilter
* @function
* @param {Object} object Canvas or Image Object on which to apply the filter
* @param {String} effect "b&w", "brightness", "transparent"
* @param {String} option : level [0...1] (for brightness), color to be replaced (for transparent)
* @return {Context2D} context object
*/
api.applyRGBFilter = function(object, effect, option) {
//create a output canvas using the given canvas or image size
var fcanvas = api.createCanvasSurface(object.width, object.height);
// get the pixels array of the give parameter
var imgpix = me.utils.getPixels(object);
// pointer to the pixels data
var pix = imgpix.data;
// apply selected effect
switch (effect) {
case "b&w": {
for ( var i = 0, n = pix.length; i < n; i += 4) {
var grayscale = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) >>> 3;
pix[i] = grayscale; // red
pix[i + 1] = grayscale; // green
pix[i + 2] = grayscale; // blue
}
break;
}
case "brightness": {
// make sure it's between 0.0 and 1.0
var brightness = Math.abs(option).clamp(0.0, 1.0);
for ( var i = 0, n = pix.length; i < n; i += 4) {
pix[i] *= brightness; // red
pix[i + 1] *= brightness; // green
pix[i + 2] *= brightness; // blue
}
break;
}
case "transparent": {
for ( var i = 0, n = pix.length; i < n; i += 4) {
if (me.utils.RGBToHex(pix[i], pix[i + 1], pix[i + 2]) === option) {
pix[i + 3] = 0;
}
}
break;
}
default:
return null;
}
// put our modified image back in the new filtered canvas
fcanvas.putImageData(imgpix, 0, 0);
// return it
return fcanvas;
};
// return our api
return api;
})();
/*---------------------------------------------------------*/
// END END END
/*---------------------------------------------------------*/
})(window);
| Fixed internal cached canvas position not being updated in case of deferred resize
| src/video/video.js | Fixed internal cached canvas position not being updated in case of deferred resize | <ide><path>rc/video/video.js
<ide> max_height / me.video.getHeight()
<ide> );
<ide> }
<del> }
<del>
<add> return;
<add> }
<ide> // make sure we have the correct relative canvas position cached
<ide> me.input.mouse.offset = me.video.getPos();
<ide> };
<ide> canvas.width = game_width_zoom = backBufferCanvas.width * scaleX;
<ide> canvas.height = game_height_zoom = backBufferCanvas.height * scaleY;
<ide>
<add> // make sure we have the correct relative canvas position cached
<add> me.input.mouse.offset = me.video.getPos();
<add>
<ide> // force a canvas repaint
<ide> api.blitSurface();
<ide> |
|
Java | apache-2.0 | c5ca661692c9b8397e7f02439e13d121113f4d0e | 0 | kalaspuffar/pdfbox,apache/pdfbox,apache/pdfbox,kalaspuffar/pdfbox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.multipdf;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSNumber;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.pdfwriter.compress.CompressParameters;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDDocumentNameDestinationDictionary;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.PDStructureElementNameTreeNode;
import org.apache.pdfbox.pdmodel.PageMode;
import org.apache.pdfbox.pdmodel.common.COSObjectable;
import org.apache.pdfbox.pdmodel.common.PDDestinationOrAction;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.pdfbox.pdmodel.common.PDNameTreeNode;
import org.apache.pdfbox.pdmodel.common.PDNumberTreeNode;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDMarkInfo;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDParentTreeValue;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;
import org.apache.pdfbox.pdmodel.graphics.color.PDOutputIntent;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.viewerpreferences.PDViewerPreferences;
/**
* This class will take a list of pdf documents and merge them, saving the
* result in a new document.
*
* @author Ben Litchfield
*/
public class PDFMergerUtility
{
/**
* Log instance.
*/
private static final Log LOG = LogFactory.getLog(PDFMergerUtility.class);
private final List<Object> sources;
private String destinationFileName;
private OutputStream destinationStream;
private boolean ignoreAcroFormErrors = false;
private PDDocumentInformation destinationDocumentInformation = null;
private PDMetadata destinationMetadata = null;
private DocumentMergeMode documentMergeMode = DocumentMergeMode.PDFBOX_LEGACY_MODE;
private AcroFormMergeMode acroFormMergeMode = AcroFormMergeMode.PDFBOX_LEGACY_MODE;
/**
* The mode to use when merging documents:
*
* <ul>
* <li>{@link DocumentMergeMode#OPTIMIZE_RESOURCES_MODE} Optimizes resource handling such as
* closing documents early. <strong>Not all document elements are merged</strong> compared to
* the PDFBOX_LEGACY_MODE. Currently supported are:
* <ul>
* <li>Page content and resources
* </ul>
* <li>{@link DocumentMergeMode#PDFBOX_LEGACY_MODE} Keeps all files open until the
* merge has been completed. This is currently necessary to merge documents
* containing a Structure Tree.
* </ul>
*/
public enum DocumentMergeMode
{
OPTIMIZE_RESOURCES_MODE,
PDFBOX_LEGACY_MODE
}
/**
* The mode to use when merging AcroForm between documents:
*
* <ul>
* <li>{@link AcroFormMergeMode#JOIN_FORM_FIELDS_MODE} fields with the same fully qualified name
* will be merged into one with the widget annotations of the merged fields
* becoming part of the same field.
* <li>{@link AcroFormMergeMode#PDFBOX_LEGACY_MODE} fields with the same fully qualified name
* will be renamed and treated as independent. This mode was used in versions
* of PDFBox up to 2.x.
* </ul>
*/
public enum AcroFormMergeMode
{
JOIN_FORM_FIELDS_MODE,
PDFBOX_LEGACY_MODE
}
/**
* Instantiate a new PDFMergerUtility.
*/
public PDFMergerUtility()
{
sources = new ArrayList<>();
}
/**
* Get the merge mode to be used for merging AcroForms between documents
*
* {@link AcroFormMergeMode}
*/
public AcroFormMergeMode getAcroFormMergeMode()
{
return acroFormMergeMode;
}
/**
* Set the merge mode to be used for merging AcroForms between documents
*
* {@link AcroFormMergeMode}
*/
public void setAcroFormMergeMode(AcroFormMergeMode theAcroFormMergeMode)
{
this.acroFormMergeMode = theAcroFormMergeMode;
}
/**
* Get the merge mode to be used for merging documents
*
* {@link DocumentMergeMode}
*/
public DocumentMergeMode getDocumentMergeMode()
{
return documentMergeMode;
}
/**
* Set the merge mode to be used for merging documents
*
* {@link DocumentMergeMode}
*/
public void setDocumentMergeMode(DocumentMergeMode theDocumentMergeMode)
{
this.documentMergeMode = theDocumentMergeMode;
}
/**
* Set the mode to be used for merging the documents
*
* {@link DocumentMergeMode}
*/
public void setAcroFormMergeMode(DocumentMergeMode theDocumentMergeMode)
{
this.documentMergeMode = theDocumentMergeMode;
}
/**
* Get the name of the destination file.
*
* @return Returns the destination.
*/
public String getDestinationFileName()
{
return destinationFileName;
}
/**
* Set the name of the destination file.
*
* @param destination The destination to set.
*/
public void setDestinationFileName(String destination)
{
destinationFileName = destination;
}
/**
* Get the destination OutputStream.
*
* @return Returns the destination OutputStream.
*/
public OutputStream getDestinationStream()
{
return destinationStream;
}
/**
* Set the destination OutputStream.
*
* @param destStream The destination to set.
*/
public void setDestinationStream(OutputStream destStream)
{
destinationStream = destStream;
}
/**
* Get the destination document information that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
* }. The default is null, which means that it is ignored.
*
* @return The destination document information.
*/
public PDDocumentInformation getDestinationDocumentInformation()
{
return destinationDocumentInformation;
}
/**
* Set the destination document information that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
* }. The default is null, which means that it is ignored.
*
* @param info The destination document information.
*/
public void setDestinationDocumentInformation(PDDocumentInformation info)
{
destinationDocumentInformation = info;
}
/**
* Set the destination metadata that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
* }. The default is null, which means that it is ignored.
*
* @return The destination metadata.
*/
public PDMetadata getDestinationMetadata()
{
return destinationMetadata;
}
/**
* Set the destination metadata that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
* }. The default is null, which means that it is ignored.
*
* @param meta The destination metadata.
*/
public void setDestinationMetadata(PDMetadata meta)
{
destinationMetadata = meta;
}
/**
* Add a source file to the list of files to merge.
*
* @param source Full path and file name of source document.
*
* @throws FileNotFoundException If the file doesn't exist
*/
public void addSource(String source) throws FileNotFoundException
{
addSource(new File(source));
}
/**
* Add a source file to the list of files to merge.
*
* @param source File representing source document
*
* @throws FileNotFoundException If the file doesn't exist
*/
public void addSource(File source) throws FileNotFoundException
{
sources.add(source);
}
/**
* Add a source to the list of documents to merge.
*
* @param source InputStream representing source document
*/
public void addSource(InputStream source)
{
sources.add(source);
}
/**
* Add a list of sources to the list of documents to merge.
*
* @param sourcesList List of InputStream objects representing source
* documents
*/
public void addSources(List<InputStream> sourcesList)
{
sources.addAll(sourcesList);
}
/**
* Merge the list of source documents, saving the result in the destination
* file.
*
* @param memUsageSetting defines how memory is used for buffering PDF streams;
* in case of <code>null</code> unrestricted main memory is used
*
* @throws IOException If there is an error saving the document.
*/
public void mergeDocuments(MemoryUsageSetting memUsageSetting) throws IOException
{
mergeDocuments(memUsageSetting, CompressParameters.DEFAULT_COMPRESSION);
}
/**
* Merge the list of source documents, saving the result in the destination file.
*
* @param memUsageSetting defines how memory is used for buffering PDF streams; in case of <code>null</code>
* unrestricted main memory is used
* @param compressParameters defines if compressed object streams are enabled
*
* @throws IOException If there is an error saving the document.
*/
public void mergeDocuments(MemoryUsageSetting memUsageSetting, CompressParameters compressParameters) throws IOException
{
if (documentMergeMode == DocumentMergeMode.PDFBOX_LEGACY_MODE)
{
legacyMergeDocuments(memUsageSetting, compressParameters);
}
else if (documentMergeMode == DocumentMergeMode.OPTIMIZE_RESOURCES_MODE)
{
optimizedMergeDocuments(memUsageSetting, compressParameters);
}
}
private void optimizedMergeDocuments(MemoryUsageSetting memUsageSetting,
CompressParameters compressParameters) throws IOException
{
try (PDDocument destination = new PDDocument(memUsageSetting))
{
PDFCloneUtility cloner = new PDFCloneUtility(destination);
for (Object sourceObject : sources)
{
PDDocument sourceDoc = null;
try
{
if (sourceObject instanceof File)
{
sourceDoc = Loader.loadPDF((File) sourceObject, memUsageSetting);
}
else
{
sourceDoc = Loader.loadPDF((InputStream) sourceObject, memUsageSetting);
}
for (PDPage page : sourceDoc.getPages())
{
PDPage newPage = new PDPage(
(COSDictionary) cloner.cloneForNewDocument(page.getCOSObject()));
newPage.setCropBox(page.getCropBox());
newPage.setMediaBox(page.getMediaBox());
newPage.setRotation(page.getRotation());
PDResources resources = page.getResources();
if (resources != null)
{
// this is smart enough to just create references for resources that are used on multiple
// pages
newPage.setResources(new PDResources(
(COSDictionary) cloner.cloneForNewDocument(resources)));
}
else
{
newPage.setResources(new PDResources());
}
destination.addPage(newPage);
}
}
finally
{
IOUtils.closeQuietly(sourceDoc);
}
}
if (destinationStream == null)
{
destination.save(destinationFileName, compressParameters);
}
else
{
destination.save(destinationStream, compressParameters);
}
}
}
/**
* Merge the list of source documents, saving the result in the destination
* file.
*
* @param memUsageSetting defines how memory is used for buffering PDF streams;
* in case of <code>null</code> unrestricted main memory is used
*
* @throws IOException If there is an error saving the document.
*/
private void legacyMergeDocuments(MemoryUsageSetting memUsageSetting,
CompressParameters compressParameters) throws IOException
{
if (sources != null && !sources.isEmpty())
{
// Make sure that:
// - first Exception is kept
// - all PDDocuments are closed
// - all FileInputStreams are closed
// - there's a way to see which errors occurred
List<PDDocument> tobeclosed = new ArrayList<>(sources.size());
MemoryUsageSetting partitionedMemSetting = memUsageSetting != null ?
memUsageSetting.getPartitionedCopy(sources.size()+1) :
MemoryUsageSetting.setupMainMemoryOnly();
try (PDDocument destination = new PDDocument(partitionedMemSetting))
{
for (Object sourceObject : sources)
{
PDDocument sourceDoc = null;
if (sourceObject instanceof File)
{
sourceDoc = Loader.loadPDF((File) sourceObject, partitionedMemSetting);
}
else
{
sourceDoc = Loader.loadPDF((InputStream) sourceObject,
partitionedMemSetting);
}
tobeclosed.add(sourceDoc);
appendDocument(destination, sourceDoc);
}
// optionally set meta data
if (destinationDocumentInformation != null)
{
destination.setDocumentInformation(destinationDocumentInformation);
}
if (destinationMetadata != null)
{
destination.getDocumentCatalog().setMetadata(destinationMetadata);
}
if (destinationStream == null)
{
destination.save(destinationFileName, compressParameters);
}
else
{
destination.save(destinationStream, compressParameters);
}
}
finally
{
for (PDDocument doc : tobeclosed)
{
IOUtils.closeAndLogException(doc, LOG, "PDDocument", null);
}
}
}
}
/**
* append all pages from source to destination.
*
* @param destination the document to receive the pages
* @param source the document originating the new pages
*
* @throws IOException If there is an error accessing data from either
* document.
*/
public void appendDocument(PDDocument destination, PDDocument source) throws IOException
{
if (source.getDocument().isClosed())
{
throw new IOException("Error: source PDF is closed.");
}
if (destination.getDocument().isClosed())
{
throw new IOException("Error: destination PDF is closed.");
}
PDDocumentCatalog destCatalog = destination.getDocumentCatalog();
PDDocumentCatalog srcCatalog = source.getDocumentCatalog();
if (isDynamicXfa(srcCatalog.getAcroForm()))
{
throw new IOException("Error: can't merge source document containing dynamic XFA form content.");
}
PDDocumentInformation destInfo = destination.getDocumentInformation();
PDDocumentInformation srcInfo = source.getDocumentInformation();
mergeInto(srcInfo.getCOSObject(), destInfo.getCOSObject(), Collections.<COSName>emptySet());
// use the highest version number for the resulting pdf
float destVersion = destination.getVersion();
float srcVersion = source.getVersion();
if (destVersion < srcVersion)
{
destination.setVersion(srcVersion);
}
int pageIndexOpenActionDest = -1;
if (destCatalog.getOpenAction() == null)
{
// PDFBOX-3972: get local dest page index, it must be reassigned after the page cloning
PDDestinationOrAction openAction = null;
try
{
openAction = srcCatalog.getOpenAction();
}
catch (IOException ex)
{
// PDFBOX-4223
LOG.error("Invalid OpenAction ignored", ex);
}
PDDestination openActionDestination = null;
if (openAction instanceof PDActionGoTo)
{
openActionDestination = ((PDActionGoTo) openAction).getDestination();
}
else if (openAction instanceof PDDestination)
{
openActionDestination = (PDDestination) openAction;
}
// note that it can also be something else, e.g. PDActionJavaScript, then do nothing
if (openActionDestination instanceof PDPageDestination)
{
PDPage page = ((PDPageDestination) openActionDestination).getPage();
if (page != null)
{
pageIndexOpenActionDest = srcCatalog.getPages().indexOf(page);
}
}
destCatalog.setOpenAction(openAction);
}
PDFCloneUtility cloner = new PDFCloneUtility(destination);
mergeAcroForm(cloner, destCatalog, srcCatalog);
COSArray destThreads = (COSArray) destCatalog.getCOSObject().getDictionaryObject(COSName.THREADS);
COSArray srcThreads = (COSArray) cloner.cloneForNewDocument(destCatalog.getCOSObject().getDictionaryObject(
COSName.THREADS));
if (destThreads == null)
{
destCatalog.getCOSObject().setItem(COSName.THREADS, srcThreads);
}
else
{
destThreads.addAll(srcThreads);
}
PDDocumentNameDictionary destNames = destCatalog.getNames();
PDDocumentNameDictionary srcNames = srcCatalog.getNames();
if (srcNames != null)
{
if (destNames == null)
{
destCatalog.getCOSObject().setItem(COSName.NAMES, cloner.cloneForNewDocument(srcNames));
}
else
{
cloner.cloneMerge(srcNames, destNames);
}
}
if (destNames != null && destNames.getCOSObject().containsKey(COSName.ID_TREE))
{
// found in 001031.pdf from PDFBOX-4417 and doesn't belong there
destNames.getCOSObject().removeItem(COSName.ID_TREE);
LOG.warn("Removed /IDTree from /Names dictionary, doesn't belong there");
}
PDDocumentNameDestinationDictionary destDests = destCatalog.getDests();
PDDocumentNameDestinationDictionary srcDests = srcCatalog.getDests();
if (srcDests != null)
{
if (destDests == null)
{
destCatalog.getCOSObject().setItem(COSName.DESTS, cloner.cloneForNewDocument(srcDests));
}
else
{
cloner.cloneMerge(srcDests, destDests);
}
}
PDDocumentOutline destOutline = destCatalog.getDocumentOutline();
PDDocumentOutline srcOutline = srcCatalog.getDocumentOutline();
if (srcOutline != null)
{
if (destOutline == null || destOutline.getFirstChild() == null)
{
PDDocumentOutline cloned = new PDDocumentOutline((COSDictionary) cloner.cloneForNewDocument(srcOutline));
destCatalog.setDocumentOutline(cloned);
}
else
{
// search last sibling for dest, because /Last entry is sometimes wrong
PDOutlineItem destLastOutlineItem = destOutline.getFirstChild();
while (destLastOutlineItem.getNextSibling() != null)
{
destLastOutlineItem = destLastOutlineItem.getNextSibling();
}
for (PDOutlineItem item : srcOutline.children())
{
// get each child, clone its dictionary, remove siblings info,
// append outline item created from there
COSDictionary clonedDict = (COSDictionary) cloner.cloneForNewDocument(item);
clonedDict.removeItem(COSName.PREV);
clonedDict.removeItem(COSName.NEXT);
PDOutlineItem clonedItem = new PDOutlineItem(clonedDict);
destLastOutlineItem.insertSiblingAfter(clonedItem);
destLastOutlineItem = destLastOutlineItem.getNextSibling();
}
}
}
PageMode destPageMode = destCatalog.getPageMode();
PageMode srcPageMode = srcCatalog.getPageMode();
if (destPageMode == null)
{
destCatalog.setPageMode(srcPageMode);
}
COSDictionary destLabels = destCatalog.getCOSObject().getCOSDictionary(COSName.PAGE_LABELS);
COSDictionary srcLabels = srcCatalog.getCOSObject().getCOSDictionary(COSName.PAGE_LABELS);
if (srcLabels != null)
{
int destPageCount = destination.getNumberOfPages();
COSArray destNums;
if (destLabels == null)
{
destLabels = new COSDictionary();
destNums = new COSArray();
destLabels.setItem(COSName.NUMS, destNums);
destCatalog.getCOSObject().setItem(COSName.PAGE_LABELS, destLabels);
}
else
{
destNums = (COSArray) destLabels.getDictionaryObject(COSName.NUMS);
}
COSArray srcNums = (COSArray) srcLabels.getDictionaryObject(COSName.NUMS);
if (srcNums != null)
{
int startSize = destNums.size();
for (int i = 0; i < srcNums.size(); i += 2)
{
COSBase base = srcNums.getObject(i);
if (!(base instanceof COSNumber))
{
LOG.error("page labels ignored, index " + i + " should be a number, but is " + base);
// remove what we added
while (destNums.size() > startSize)
{
destNums.remove(startSize);
}
break;
}
COSNumber labelIndex = (COSNumber) base;
long labelIndexValue = labelIndex.intValue();
destNums.add(COSInteger.get(labelIndexValue + destPageCount));
destNums.add(cloner.cloneForNewDocument(srcNums.getObject(i + 1)));
}
}
}
COSStream destMetadata = destCatalog.getCOSObject().getCOSStream(COSName.METADATA);
COSStream srcMetadata = srcCatalog.getCOSObject().getCOSStream(COSName.METADATA);
if (destMetadata == null && srcMetadata != null)
{
try
{
PDStream newStream = new PDStream(destination, srcMetadata.createInputStream(), (COSName) null);
mergeInto(srcMetadata, newStream.getCOSObject(),
new HashSet<>(Arrays.asList(COSName.FILTER, COSName.LENGTH)));
destCatalog.getCOSObject().setItem(COSName.METADATA, newStream);
}
catch (IOException ex)
{
// PDFBOX-4227 cleartext XMP stream with /Flate
LOG.error("Metadata skipped because it could not be read", ex);
}
}
COSDictionary destOCP = destCatalog.getCOSObject().getCOSDictionary(COSName.OCPROPERTIES);
COSDictionary srcOCP = srcCatalog.getCOSObject().getCOSDictionary(COSName.OCPROPERTIES);
if (destOCP == null && srcOCP != null)
{
destCatalog.getCOSObject().setItem(COSName.OCPROPERTIES, cloner.cloneForNewDocument(srcOCP));
}
else if (destOCP != null && srcOCP != null)
{
cloner.cloneMerge(srcOCP, destOCP);
}
mergeOutputIntents(cloner, srcCatalog, destCatalog);
// merge logical structure hierarchy
boolean mergeStructTree = false;
int destParentTreeNextKey = -1;
Map<Integer, COSObjectable> srcNumberTreeAsMap = null;
Map<Integer, COSObjectable> destNumberTreeAsMap = null;
PDStructureTreeRoot srcStructTree = srcCatalog.getStructureTreeRoot();
PDStructureTreeRoot destStructTree = destCatalog.getStructureTreeRoot();
if (destStructTree == null && srcStructTree != null)
{
// create a dummy structure tree in the destination, so that the source
// tree is cloned. (We can't just copy the tree reference due to PDFBOX-3999)
destStructTree = new PDStructureTreeRoot();
destCatalog.setStructureTreeRoot(destStructTree);
destStructTree.setParentTree(new PDNumberTreeNode(PDParentTreeValue.class));
// PDFBOX-4429: remove bogus StructParent(s)
for (PDPage page : destCatalog.getPages())
{
page.getCOSObject().removeItem(COSName.STRUCT_PARENTS);
for (PDAnnotation ann : page.getAnnotations())
{
ann.getCOSObject().removeItem(COSName.STRUCT_PARENT);
}
}
}
if (destStructTree != null)
{
PDNumberTreeNode destParentTree = destStructTree.getParentTree();
destParentTreeNextKey = destStructTree.getParentTreeNextKey();
if (destParentTree != null)
{
destNumberTreeAsMap = getNumberTreeAsMap(destParentTree);
if (destParentTreeNextKey < 0)
{
if (destNumberTreeAsMap.isEmpty())
{
destParentTreeNextKey = 0;
}
else
{
destParentTreeNextKey = Collections.max(destNumberTreeAsMap.keySet()) + 1;
}
}
if (destParentTreeNextKey >= 0 && srcStructTree != null)
{
PDNumberTreeNode srcParentTree = srcStructTree.getParentTree();
if (srcParentTree != null)
{
srcNumberTreeAsMap = getNumberTreeAsMap(srcParentTree);
if (!srcNumberTreeAsMap.isEmpty())
{
mergeStructTree = true;
}
}
}
}
}
Map<COSDictionary, COSDictionary> objMapping = new HashMap<>();
int pageIndex = 0;
for (PDPage page : srcCatalog.getPages())
{
PDPage newPage = new PDPage((COSDictionary) cloner.cloneForNewDocument(page.getCOSObject()));
if (!mergeStructTree)
{
// PDFBOX-4429: remove bogus StructParent(s)
newPage.getCOSObject().removeItem(COSName.STRUCT_PARENTS);
for (PDAnnotation ann : newPage.getAnnotations())
{
ann.getCOSObject().removeItem(COSName.STRUCT_PARENT);
}
}
newPage.setCropBox(page.getCropBox());
newPage.setMediaBox(page.getMediaBox());
newPage.setRotation(page.getRotation());
PDResources resources = page.getResources();
if (resources != null)
{
// this is smart enough to just create references for resources that are used on multiple pages
newPage.setResources(new PDResources((COSDictionary) cloner.cloneForNewDocument(resources)));
}
else
{
newPage.setResources(new PDResources());
}
if (mergeStructTree)
{
// add the value of the destination ParentTreeNextKey to every source element
// StructParent(s) value so that these don't overlap with the existing values
updateStructParentEntries(newPage, destParentTreeNextKey);
objMapping.put(page.getCOSObject(), newPage.getCOSObject());
List<PDAnnotation> oldAnnots = page.getAnnotations();
List<PDAnnotation> newAnnots = newPage.getAnnotations();
for (int i = 0; i < oldAnnots.size(); i++)
{
objMapping.put(oldAnnots.get(i).getCOSObject(), newAnnots.get(i).getCOSObject());
}
// TODO update mapping for XObjects
}
destination.addPage(newPage);
if (pageIndex == pageIndexOpenActionDest)
{
// PDFBOX-3972: reassign the page.
// The openAction is either a PDActionGoTo or a PDPageDestination
PDDestinationOrAction openAction = destCatalog.getOpenAction();
PDPageDestination pageDestination;
if (openAction instanceof PDActionGoTo)
{
pageDestination = (PDPageDestination) ((PDActionGoTo) openAction).getDestination();
}
else
{
pageDestination = (PDPageDestination) openAction;
}
pageDestination.setPage(newPage);
}
++pageIndex;
}
if (mergeStructTree)
{
updatePageReferences(cloner, srcNumberTreeAsMap, objMapping);
int maxSrcKey = -1;
for (Map.Entry<Integer, COSObjectable> entry : srcNumberTreeAsMap.entrySet())
{
int srcKey = entry.getKey();
maxSrcKey = Math.max(srcKey, maxSrcKey);
destNumberTreeAsMap.put(destParentTreeNextKey + srcKey, cloner.cloneForNewDocument(entry.getValue()));
}
destParentTreeNextKey += maxSrcKey + 1;
PDNumberTreeNode newParentTreeNode = new PDNumberTreeNode(PDParentTreeValue.class);
// Note that all elements are stored flatly. This could become a problem for large files
// when these are opened in a viewer that uses the tagging information.
// If this happens, then PDNumberTreeNode should be improved with a convenience method that
// stores the map into a B+Tree, see https://en.wikipedia.org/wiki/B+_tree
newParentTreeNode.setNumbers(destNumberTreeAsMap);
destStructTree.setParentTree(newParentTreeNode);
destStructTree.setParentTreeNextKey(destParentTreeNextKey);
mergeKEntries(cloner, srcStructTree, destStructTree);
mergeRoleMap(srcStructTree, destStructTree);
mergeIDTree(cloner, srcStructTree, destStructTree);
mergeMarkInfo(destCatalog, srcCatalog);
mergeLanguage(destCatalog, srcCatalog);
mergeViewerPreferences(destCatalog, srcCatalog);
}
}
private void mergeViewerPreferences(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
PDViewerPreferences srcViewerPreferences = srcCatalog.getViewerPreferences();
if (srcViewerPreferences == null)
{
return;
}
PDViewerPreferences destViewerPreferences = destCatalog.getViewerPreferences();
if (destViewerPreferences == null)
{
destViewerPreferences = new PDViewerPreferences(new COSDictionary());
destCatalog.setViewerPreferences(destViewerPreferences);
}
mergeInto(srcViewerPreferences.getCOSObject(), destViewerPreferences.getCOSObject(),
Collections.<COSName>emptySet());
// check the booleans - set to true if one is set and true
if (srcViewerPreferences.hideToolbar() || destViewerPreferences.hideToolbar())
{
destViewerPreferences.setHideToolbar(true);
}
if (srcViewerPreferences.hideMenubar() || destViewerPreferences.hideMenubar())
{
destViewerPreferences.setHideMenubar(true);
}
if (srcViewerPreferences.hideWindowUI() || destViewerPreferences.hideWindowUI())
{
destViewerPreferences.setHideWindowUI(true);
}
if (srcViewerPreferences.fitWindow() || destViewerPreferences.fitWindow())
{
destViewerPreferences.setFitWindow(true);
}
if (srcViewerPreferences.centerWindow() || destViewerPreferences.centerWindow())
{
destViewerPreferences.setCenterWindow(true);
}
if (srcViewerPreferences.displayDocTitle() || destViewerPreferences.displayDocTitle())
{
destViewerPreferences.setDisplayDocTitle(true);
}
}
private void mergeLanguage(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
if (destCatalog.getLanguage() == null && srcCatalog.getLanguage() != null)
{
destCatalog.setLanguage(srcCatalog.getLanguage());
}
}
private void mergeMarkInfo(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
PDMarkInfo destMark = destCatalog.getMarkInfo();
PDMarkInfo srcMark = srcCatalog.getMarkInfo();
if (destMark == null)
{
destMark = new PDMarkInfo();
}
if (srcMark == null)
{
srcMark = new PDMarkInfo();
}
destMark.setMarked(true);
destMark.setSuspect(srcMark.isSuspect() || destMark.isSuspect());
destMark.setSuspect(srcMark.usesUserProperties() || destMark.usesUserProperties());
destCatalog.setMarkInfo(destMark);
}
private void mergeKEntries(PDFCloneUtility cloner,
PDStructureTreeRoot srcStructTree,
PDStructureTreeRoot destStructTree) throws IOException
{
// make new /K with array that has the input /K entries
COSArray newKArray = new COSArray();
if (destStructTree.getK() != null)
{
COSBase base = destStructTree.getK();
if (base instanceof COSArray)
{
newKArray.addAll((COSArray) base);
}
else
{
newKArray.add(base);
}
}
if (srcStructTree.getK() != null)
{
COSBase base = cloner.cloneForNewDocument(srcStructTree.getK());
if (base instanceof COSArray)
{
newKArray.addAll((COSArray) base);
}
else
{
newKArray.add(base);
}
}
if (newKArray.size() > 0)
{
COSDictionary kDictLevel0 = new COSDictionary();
updateParentEntry(newKArray, kDictLevel0);
kDictLevel0.setItem(COSName.K, newKArray);
kDictLevel0.setItem(COSName.P, destStructTree);
kDictLevel0.setItem(COSName.S, COSName.DOCUMENT);
destStructTree.setK(kDictLevel0);
}
}
private void mergeIDTree(PDFCloneUtility cloner,
PDStructureTreeRoot srcStructTree,
PDStructureTreeRoot destStructTree) throws IOException
{
PDNameTreeNode<PDStructureElement> srcIDTree = srcStructTree.getIDTree();
PDNameTreeNode<PDStructureElement> destIDTree = destStructTree.getIDTree();
if (srcIDTree == null)
{
return;
}
if (destIDTree == null)
{
destIDTree = new PDStructureElementNameTreeNode();
}
Map<String, PDStructureElement> srcNames = getIDTreeAsMap(srcIDTree);
Map<String, PDStructureElement> destNames = getIDTreeAsMap(destIDTree);
for (Map.Entry<String, PDStructureElement> entry : srcNames.entrySet())
{
if (destNames.containsKey(entry.getKey()))
{
LOG.warn("key " + entry.getKey() + " already exists in destination IDTree");
}
else
{
destNames.put(entry.getKey(),
new PDStructureElement((COSDictionary) cloner.cloneForNewDocument(entry.getValue().getCOSObject())));
}
}
destIDTree = new PDStructureElementNameTreeNode();
destIDTree.setNames(destNames);
destStructTree.setIDTree(destIDTree);
// Note that all elements are stored flatly. This could become a problem for large files
// when these are opened in a viewer that uses the tagging information.
// If this happens, then PDNameTreeNode should be improved with a convenience method that
// stores the map into a B+Tree, see https://en.wikipedia.org/wiki/B+_tree
}
// PDNameTreeNode.getNames() only brings one level, this is why we need this
// might be made public at a later time, or integrated into PDNameTreeNode with template.
static Map<String, PDStructureElement> getIDTreeAsMap(PDNameTreeNode<PDStructureElement> idTree)
throws IOException
{
Map<String, PDStructureElement> names = idTree.getNames();
if (names == null)
{
names = new LinkedHashMap<>();
}
else
{
// must copy because the map is read only
names = new LinkedHashMap<>(names);
}
List<PDNameTreeNode<PDStructureElement>> kids = idTree.getKids();
if (kids != null)
{
for (PDNameTreeNode<PDStructureElement> kid : kids)
{
names.putAll(getIDTreeAsMap(kid));
}
}
return names;
}
// PDNumberTreeNode.getNumbers() only brings one level, this is why we need this
// might be made public at a later time, or integrated into PDNumberTreeNode.
static Map<Integer, COSObjectable> getNumberTreeAsMap(PDNumberTreeNode tree)
throws IOException
{
Map<Integer, COSObjectable> numbers = tree.getNumbers();
if (numbers == null)
{
numbers = new LinkedHashMap<>();
}
else
{
// must copy because the map is read only
numbers = new LinkedHashMap<>(numbers);
}
List<PDNumberTreeNode> kids = tree.getKids();
if (kids != null)
{
for (PDNumberTreeNode kid : kids)
{
numbers.putAll(getNumberTreeAsMap(kid));
}
}
return numbers;
}
private void mergeRoleMap(PDStructureTreeRoot srcStructTree, PDStructureTreeRoot destStructTree)
{
COSDictionary srcDict = srcStructTree.getCOSObject().getCOSDictionary(COSName.ROLE_MAP);
COSDictionary destDict = destStructTree.getCOSObject().getCOSDictionary(COSName.ROLE_MAP);
if (srcDict == null)
{
return;
}
if (destDict == null)
{
destStructTree.getCOSObject().setItem(COSName.ROLE_MAP, srcDict); // clone not needed
return;
}
for (Map.Entry<COSName, COSBase> entry : srcDict.entrySet())
{
COSBase destValue = destDict.getDictionaryObject(entry.getKey());
if (destValue != null && destValue.equals(entry.getValue()))
{
// already exists, but identical
continue;
}
if (destDict.containsKey(entry.getKey()))
{
LOG.warn("key " + entry.getKey() + " already exists in destination RoleMap");
}
else
{
destDict.setItem(entry.getKey(), entry.getValue());
}
}
}
private void mergeAcroForm(PDFCloneUtility cloner, PDDocumentCatalog destCatalog,
PDDocumentCatalog srcCatalog ) throws IOException
{
try
{
PDAcroForm destAcroForm = destCatalog.getAcroForm();
PDAcroForm srcAcroForm = srcCatalog.getAcroForm();
if (destAcroForm == null && srcAcroForm != null)
{
destCatalog.getCOSObject().setItem(COSName.ACRO_FORM,
cloner.cloneForNewDocument(srcAcroForm.getCOSObject()));
}
else
{
if (srcAcroForm != null)
{
if (acroFormMergeMode == AcroFormMergeMode.PDFBOX_LEGACY_MODE)
{
acroFormLegacyMode(cloner, destAcroForm, srcAcroForm);
}
else if (acroFormMergeMode == AcroFormMergeMode.JOIN_FORM_FIELDS_MODE)
{
acroFormJoinFieldsMode(cloner, destAcroForm, srcAcroForm);
}
}
}
}
catch (IOException e)
{
// if we are not ignoring exceptions, we'll re-throw this
if (!ignoreAcroFormErrors)
{
throw new IOException(e);
}
}
}
/*
* Merge the contents of the source form into the destination form for the
* destination file.
*
* @param cloner the object cloner for the destination document
* @param destAcroForm the destination form
* @param srcAcroForm the source form
* @throws IOException If an error occurs while adding the field.
*/
private void acroFormJoinFieldsMode(PDFCloneUtility cloner, PDAcroForm destAcroForm, PDAcroForm srcAcroForm)
throws IOException
{
acroFormLegacyMode(cloner, destAcroForm, srcAcroForm);
}
/*
* Merge the contents of the source form into the destination form for the
* destination file.
*
* @param cloner the object cloner for the destination document
* @param destAcroForm the destination form
* @param srcAcroForm the source form
* @throws IOException If an error occurs while adding the field.
*/
private void acroFormLegacyMode(PDFCloneUtility cloner, PDAcroForm destAcroForm, PDAcroForm srcAcroForm)
throws IOException
{
List<PDField> srcFields = srcAcroForm.getFields();
COSArray destFields;
if (srcFields != null && !srcFields.isEmpty())
{
// if a form is merged multiple times using PDFBox the newly generated
// fields starting with dummyFieldName may already exist. We need to determine the last unique
// number used and increment that.
final String prefix = "dummyFieldName";
final int prefixLength = prefix.length();
for (PDField destField : destAcroForm.getFieldTree())
{
String fieldName = destField.getPartialName();
if (fieldName.startsWith(prefix))
{
nextFieldNum = Math.max(nextFieldNum, Integer.parseInt(fieldName.substring(prefixLength, fieldName.length())) + 1);
}
}
// get the destinations root fields. Could be that the entry doesn't exist
// or is of wrong type
COSBase base = destAcroForm.getCOSObject().getItem(COSName.FIELDS);
if (base instanceof COSArray)
{
destFields = (COSArray) base;
}
else
{
destFields = new COSArray();
}
for (PDField srcField : srcAcroForm.getFields())
{
COSDictionary dstField = (COSDictionary) cloner.cloneForNewDocument(srcField.getCOSObject());
// if the form already has a field with this name then we need to rename this field
// to prevent merge conflicts.
if (destAcroForm.getField(srcField.getFullyQualifiedName()) != null)
{
dstField.setString(COSName.T, prefix + nextFieldNum++);
}
destFields.add(dstField);
}
destAcroForm.getCOSObject().setItem(COSName.FIELDS,destFields);
}
}
// copy outputIntents to destination, but avoid duplicate OutputConditionIdentifier,
// except when it is missing or is named "Custom".
private void mergeOutputIntents(PDFCloneUtility cloner,
PDDocumentCatalog srcCatalog, PDDocumentCatalog destCatalog) throws IOException
{
List<PDOutputIntent> srcOutputIntents = srcCatalog.getOutputIntents();
List<PDOutputIntent> dstOutputIntents = destCatalog.getOutputIntents();
for (PDOutputIntent srcOI : srcOutputIntents)
{
String srcOCI = srcOI.getOutputConditionIdentifier();
if (srcOCI != null && !"Custom".equals(srcOCI))
{
// is that identifier already there?
boolean skip = false;
for (PDOutputIntent dstOI : dstOutputIntents)
{
if (dstOI.getOutputConditionIdentifier().equals(srcOCI))
{
skip = true;
break;
}
}
if (skip)
{
continue;
}
}
destCatalog.addOutputIntent(new PDOutputIntent((COSDictionary) cloner.cloneForNewDocument(srcOI)));
dstOutputIntents.add(srcOI);
}
}
private int nextFieldNum = 1;
/**
* Indicates if acroform errors are ignored or not.
*
* @return true if acroform errors are ignored
*/
public boolean isIgnoreAcroFormErrors()
{
return ignoreAcroFormErrors;
}
/**
* Set to true to ignore acroform errors.
*
* @param ignoreAcroFormErrorsValue true if acroform errors should be
* ignored
*/
public void setIgnoreAcroFormErrors(boolean ignoreAcroFormErrorsValue)
{
ignoreAcroFormErrors = ignoreAcroFormErrorsValue;
}
/**
* Update the Pg and Obj references to the new (merged) page.
*/
private void updatePageReferences(PDFCloneUtility cloner,
Map<Integer, COSObjectable> numberTreeAsMap,
Map<COSDictionary, COSDictionary> objMapping) throws IOException
{
for (COSObjectable obj : numberTreeAsMap.values())
{
if (obj == null)
{
continue;
}
PDParentTreeValue val = (PDParentTreeValue) obj;
COSBase base = val.getCOSObject();
if (base instanceof COSArray)
{
updatePageReferences(cloner, (COSArray) base, objMapping);
}
else
{
updatePageReferences(cloner, (COSDictionary) base, objMapping);
}
}
}
/**
* Update the Pg and Obj references to the new (merged) page.
*
* @param parentTreeEntry
* @param objMapping mapping between old and new references
*/
private void updatePageReferences(PDFCloneUtility cloner,
COSDictionary parentTreeEntry, Map<COSDictionary, COSDictionary> objMapping)
throws IOException
{
COSDictionary pageDict = parentTreeEntry.getCOSDictionary(COSName.PG);
if (objMapping.containsKey(pageDict))
{
parentTreeEntry.setItem(COSName.PG, objMapping.get(pageDict));
}
COSBase obj = parentTreeEntry.getDictionaryObject(COSName.OBJ);
if (obj instanceof COSDictionary)
{
COSDictionary objDict = (COSDictionary) obj;
if (objMapping.containsKey(objDict))
{
parentTreeEntry.setItem(COSName.OBJ, objMapping.get(objDict));
}
else
{
// PDFBOX-3999: clone objects that are not in mapping to make sure that
// these don't remain attached to the source document
COSBase item = parentTreeEntry.getItem(COSName.OBJ);
if (item instanceof COSObject)
{
LOG.debug("clone potential orphan object in structure tree: " + item +
", Type: " + objDict.getNameAsString(COSName.TYPE) +
", Subtype: " + objDict.getNameAsString(COSName.SUBTYPE) +
", T: " + objDict.getNameAsString(COSName.T));
}
else
{
// don't display in full because of stack overflow
LOG.debug("clone potential orphan object in structure tree" +
", Type: " + objDict.getNameAsString(COSName.TYPE) +
", Subtype: " + objDict.getNameAsString(COSName.SUBTYPE) +
", T: " + objDict.getNameAsString(COSName.T));
}
parentTreeEntry.setItem(COSName.OBJ, cloner.cloneForNewDocument(obj));
}
}
COSBase kSubEntry = parentTreeEntry.getDictionaryObject(COSName.K);
if (kSubEntry instanceof COSArray)
{
updatePageReferences(cloner, (COSArray) kSubEntry, objMapping);
}
else if (kSubEntry instanceof COSDictionary)
{
updatePageReferences(cloner, (COSDictionary) kSubEntry, objMapping);
}
}
private void updatePageReferences(PDFCloneUtility cloner,
COSArray parentTreeEntry, Map<COSDictionary, COSDictionary> objMapping)
throws IOException
{
for (int i = 0; i < parentTreeEntry.size(); i++)
{
COSBase subEntry = parentTreeEntry.getObject(i);
if (subEntry instanceof COSArray)
{
updatePageReferences(cloner, (COSArray) subEntry, objMapping);
}
else if (subEntry instanceof COSDictionary)
{
updatePageReferences(cloner, (COSDictionary) subEntry, objMapping);
}
}
}
/**
* Update the P reference to the new parent dictionary.
*
* @param kArray the kids array
* @param newParent the new parent
*/
private void updateParentEntry(COSArray kArray, COSDictionary newParent)
{
for (int i = 0; i < kArray.size(); i++)
{
COSBase subEntry = kArray.getObject(i);
if (subEntry instanceof COSDictionary)
{
COSDictionary dictEntry = (COSDictionary) subEntry;
if (dictEntry.getDictionaryObject(COSName.P) != null)
{
dictEntry.setItem(COSName.P, newParent);
}
}
}
}
/**
* Update the StructParents and StructParent values in a PDPage.
*
* @param page the new page
* @param structParentOffset the offset which should be applied
*/
private void updateStructParentEntries(PDPage page, int structParentOffset) throws IOException
{
if (page.getStructParents() >= 0)
{
page.setStructParents(page.getStructParents() + structParentOffset);
}
List<PDAnnotation> annots = page.getAnnotations();
List<PDAnnotation> newannots = new ArrayList<>();
for (PDAnnotation annot : annots)
{
if (annot.getStructParent() >= 0)
{
annot.setStructParent(annot.getStructParent() + structParentOffset);
}
newannots.add(annot);
}
page.setAnnotations(newannots);
}
/**
* Test for dynamic XFA content.
*
* @param acroForm the AcroForm
* @return true if there is a dynamic XFA form.
*/
private boolean isDynamicXfa(PDAcroForm acroForm)
{
return acroForm != null && acroForm.xfaIsDynamic();
}
/**
* This will add all of the dictionaries keys/values to this dictionary, but
* only if they are not in an exclusion list and if they don't already
* exist. If a key already exists in this dictionary then nothing is
* changed.
*
* @param src The source dictionary to get the keys/values from.
* @param dst The destination dictionary to merge the keys/values into.
* @param exclude Names of keys that shall be skipped.
*/
private void mergeInto(COSDictionary src, COSDictionary dst, Set<COSName> exclude)
{
for (Map.Entry<COSName, COSBase> entry : src.entrySet())
{
if (!exclude.contains(entry.getKey()) && !dst.containsKey(entry.getKey()))
{
dst.setItem(entry.getKey(), entry.getValue());
}
}
}
}
| pdfbox/src/main/java/org/apache/pdfbox/multipdf/PDFMergerUtility.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.multipdf;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSNumber;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.pdfwriter.compress.CompressParameters;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDDocumentNameDestinationDictionary;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.PDStructureElementNameTreeNode;
import org.apache.pdfbox.pdmodel.PageMode;
import org.apache.pdfbox.pdmodel.common.COSObjectable;
import org.apache.pdfbox.pdmodel.common.PDDestinationOrAction;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.pdfbox.pdmodel.common.PDNameTreeNode;
import org.apache.pdfbox.pdmodel.common.PDNumberTreeNode;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDMarkInfo;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDParentTreeValue;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;
import org.apache.pdfbox.pdmodel.graphics.color.PDOutputIntent;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.viewerpreferences.PDViewerPreferences;
/**
* This class will take a list of pdf documents and merge them, saving the
* result in a new document.
*
* @author Ben Litchfield
*/
public class PDFMergerUtility
{
/**
* Log instance.
*/
private static final Log LOG = LogFactory.getLog(PDFMergerUtility.class);
private final List<Object> sources;
private String destinationFileName;
private OutputStream destinationStream;
private boolean ignoreAcroFormErrors = false;
private PDDocumentInformation destinationDocumentInformation = null;
private PDMetadata destinationMetadata = null;
private DocumentMergeMode documentMergeMode = DocumentMergeMode.PDFBOX_LEGACY_MODE;
private AcroFormMergeMode acroFormMergeMode = AcroFormMergeMode.PDFBOX_LEGACY_MODE;
/**
* The mode to use when merging documents:
*
* <ul>
* <li>{@link DocumentMergeMode#OPTIMIZE_RESOURCES_MODE} Optimizes resource handling such as
* closing documents early. <strong>Not all document elements are merged</strong> compared to
* the PDFBOX_LEGACY_MODE. Currently supported are:
* <ul>
* <li>Page content and resources
* </ul>
* <li>{@link DocumentMergeMode#PDFBOX_LEGACY_MODE} Keeps all files open until the
* merge has been completed. This is currently necessary to merge documents
* containing a Structure Tree.
* </ul>
*/
public enum DocumentMergeMode
{
OPTIMIZE_RESOURCES_MODE,
PDFBOX_LEGACY_MODE
}
/**
* The mode to use when merging AcroForm between documents:
*
* <ul>
* <li>{@link AcroFormMergeMode#JOIN_FORM_FIELDS_MODE} fields with the same fully qualified name
* will be merged into one with the widget annotations of the merged fields
* becoming part of the same field.
* <li>{@link AcroFormMergeMode#PDFBOX_LEGACY_MODE} fields with the same fully qualified name
* will be renamed and treated as independent. This mode was used in versions
* of PDFBox up to 2.x.
* </ul>
*/
public enum AcroFormMergeMode
{
JOIN_FORM_FIELDS_MODE,
PDFBOX_LEGACY_MODE
}
/**
* Instantiate a new PDFMergerUtility.
*/
public PDFMergerUtility()
{
sources = new ArrayList<>();
}
/**
* Get the merge mode to be used for merging AcroForms between documents
*
* {@link AcroFormMergeMode}
*/
public AcroFormMergeMode getAcroFormMergeMode()
{
return acroFormMergeMode;
}
/**
* Set the merge mode to be used for merging AcroForms between documents
*
* {@link AcroFormMergeMode}
*/
public void setAcroFormMergeMode(AcroFormMergeMode theAcroFormMergeMode)
{
this.acroFormMergeMode = theAcroFormMergeMode;
}
/**
* Get the merge mode to be used for merging documents
*
* {@link DocumentMergeMode}
*/
public DocumentMergeMode getDocumentMergeMode()
{
return documentMergeMode;
}
/**
* Set the merge mode to be used for merging documents
*
* {@link DocumentMergeMode}
*/
public void setDocumentMergeMode(DocumentMergeMode theDocumentMergeMode)
{
this.documentMergeMode = theDocumentMergeMode;
}
/**
* Set the mode to be used for merging the documents
*
* {@link DocumentMergeMode}
*/
public void setAcroFormMergeMode(DocumentMergeMode theDocumentMergeMode)
{
this.documentMergeMode = theDocumentMergeMode;
}
/**
* Get the name of the destination file.
*
* @return Returns the destination.
*/
public String getDestinationFileName()
{
return destinationFileName;
}
/**
* Set the name of the destination file.
*
* @param destination The destination to set.
*/
public void setDestinationFileName(String destination)
{
destinationFileName = destination;
}
/**
* Get the destination OutputStream.
*
* @return Returns the destination OutputStream.
*/
public OutputStream getDestinationStream()
{
return destinationStream;
}
/**
* Set the destination OutputStream.
*
* @param destStream The destination to set.
*/
public void setDestinationStream(OutputStream destStream)
{
destinationStream = destStream;
}
/**
* Get the destination document information that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
* }. The default is null, which means that it is ignored.
*
* @return The destination document information.
*/
public PDDocumentInformation getDestinationDocumentInformation()
{
return destinationDocumentInformation;
}
/**
* Set the destination document information that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
* }. The default is null, which means that it is ignored.
*
* @param info The destination document information.
*/
public void setDestinationDocumentInformation(PDDocumentInformation info)
{
destinationDocumentInformation = info;
}
/**
* Set the destination metadata that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
* }. The default is null, which means that it is ignored.
*
* @return The destination metadata.
*/
public PDMetadata getDestinationMetadata()
{
return destinationMetadata;
}
/**
* Set the destination metadata that is to be set in {@link #mergeDocuments(org.apache.pdfbox.io.MemoryUsageSetting)
* }. The default is null, which means that it is ignored.
*
* @param meta The destination metadata.
*/
public void setDestinationMetadata(PDMetadata meta)
{
destinationMetadata = meta;
}
/**
* Add a source file to the list of files to merge.
*
* @param source Full path and file name of source document.
*
* @throws FileNotFoundException If the file doesn't exist
*/
public void addSource(String source) throws FileNotFoundException
{
addSource(new File(source));
}
/**
* Add a source file to the list of files to merge.
*
* @param source File representing source document
*
* @throws FileNotFoundException If the file doesn't exist
*/
public void addSource(File source) throws FileNotFoundException
{
sources.add(source);
}
/**
* Add a source to the list of documents to merge.
*
* @param source InputStream representing source document
*/
public void addSource(InputStream source)
{
sources.add(source);
}
/**
* Add a list of sources to the list of documents to merge.
*
* @param sourcesList List of InputStream objects representing source
* documents
*/
public void addSources(List<InputStream> sourcesList)
{
sources.addAll(sourcesList);
}
/**
* Merge the list of source documents, saving the result in the destination
* file.
*
* @param memUsageSetting defines how memory is used for buffering PDF streams;
* in case of <code>null</code> unrestricted main memory is used
*
* @throws IOException If there is an error saving the document.
*/
public void mergeDocuments(MemoryUsageSetting memUsageSetting) throws IOException
{
mergeDocuments(memUsageSetting, CompressParameters.DEFAULT_COMPRESSION);
}
/**
* Merge the list of source documents, saving the result in the destination file.
*
* @param memUsageSetting defines how memory is used for buffering PDF streams; in case of <code>null</code>
* unrestricted main memory is used
* @param compressParameters defines if compressed object streams are enabled
*
* @throws IOException If there is an error saving the document.
*/
public void mergeDocuments(MemoryUsageSetting memUsageSetting, CompressParameters compressParameters) throws IOException
{
if (documentMergeMode == DocumentMergeMode.PDFBOX_LEGACY_MODE)
{
legacyMergeDocuments(memUsageSetting, compressParameters);
}
else if (documentMergeMode == DocumentMergeMode.OPTIMIZE_RESOURCES_MODE)
{
optimizedMergeDocuments(memUsageSetting, compressParameters);
}
}
private void optimizedMergeDocuments(MemoryUsageSetting memUsageSetting,
CompressParameters compressParameters) throws IOException
{
try (PDDocument destination = new PDDocument(memUsageSetting))
{
PDFCloneUtility cloner = new PDFCloneUtility(destination);
for (Object sourceObject : sources)
{
PDDocument sourceDoc = null;
try
{
if (sourceObject instanceof File)
{
sourceDoc = Loader.loadPDF((File) sourceObject, memUsageSetting);
}
else
{
sourceDoc = Loader.loadPDF((InputStream) sourceObject, memUsageSetting);
}
for (PDPage page : sourceDoc.getPages())
{
PDPage newPage = new PDPage(
(COSDictionary) cloner.cloneForNewDocument(page.getCOSObject()));
newPage.setCropBox(page.getCropBox());
newPage.setMediaBox(page.getMediaBox());
newPage.setRotation(page.getRotation());
PDResources resources = page.getResources();
if (resources != null)
{
// this is smart enough to just create references for resources that are used on multiple
// pages
newPage.setResources(new PDResources(
(COSDictionary) cloner.cloneForNewDocument(resources)));
}
else
{
newPage.setResources(new PDResources());
}
destination.addPage(newPage);
}
}
finally
{
IOUtils.closeQuietly(sourceDoc);
}
}
if (destinationStream == null)
{
destination.save(destinationFileName, compressParameters);
}
else
{
destination.save(destinationStream, compressParameters);
}
}
}
/**
* Merge the list of source documents, saving the result in the destination
* file.
*
* @param memUsageSetting defines how memory is used for buffering PDF streams;
* in case of <code>null</code> unrestricted main memory is used
*
* @throws IOException If there is an error saving the document.
*/
private void legacyMergeDocuments(MemoryUsageSetting memUsageSetting,
CompressParameters compressParameters) throws IOException
{
if (sources != null && !sources.isEmpty())
{
// Make sure that:
// - first Exception is kept
// - all PDDocuments are closed
// - all FileInputStreams are closed
// - there's a way to see which errors occurred
List<PDDocument> tobeclosed = new ArrayList<>();
MemoryUsageSetting partitionedMemSetting = memUsageSetting != null ?
memUsageSetting.getPartitionedCopy(sources.size()+1) :
MemoryUsageSetting.setupMainMemoryOnly();
try (PDDocument destination = new PDDocument(partitionedMemSetting))
{
for (Object sourceObject : sources)
{
PDDocument sourceDoc = null;
if (sourceObject instanceof File)
{
sourceDoc = Loader.loadPDF((File) sourceObject, partitionedMemSetting);
}
else
{
sourceDoc = Loader.loadPDF((InputStream) sourceObject,
partitionedMemSetting);
}
tobeclosed.add(sourceDoc);
appendDocument(destination, sourceDoc);
}
// optionally set meta data
if (destinationDocumentInformation != null)
{
destination.setDocumentInformation(destinationDocumentInformation);
}
if (destinationMetadata != null)
{
destination.getDocumentCatalog().setMetadata(destinationMetadata);
}
if (destinationStream == null)
{
destination.save(destinationFileName, compressParameters);
}
else
{
destination.save(destinationStream, compressParameters);
}
}
finally
{
for (PDDocument doc : tobeclosed)
{
IOUtils.closeAndLogException(doc, LOG, "PDDocument", null);
}
}
}
}
/**
* append all pages from source to destination.
*
* @param destination the document to receive the pages
* @param source the document originating the new pages
*
* @throws IOException If there is an error accessing data from either
* document.
*/
public void appendDocument(PDDocument destination, PDDocument source) throws IOException
{
if (source.getDocument().isClosed())
{
throw new IOException("Error: source PDF is closed.");
}
if (destination.getDocument().isClosed())
{
throw new IOException("Error: destination PDF is closed.");
}
PDDocumentCatalog destCatalog = destination.getDocumentCatalog();
PDDocumentCatalog srcCatalog = source.getDocumentCatalog();
if (isDynamicXfa(srcCatalog.getAcroForm()))
{
throw new IOException("Error: can't merge source document containing dynamic XFA form content.");
}
PDDocumentInformation destInfo = destination.getDocumentInformation();
PDDocumentInformation srcInfo = source.getDocumentInformation();
mergeInto(srcInfo.getCOSObject(), destInfo.getCOSObject(), Collections.<COSName>emptySet());
// use the highest version number for the resulting pdf
float destVersion = destination.getVersion();
float srcVersion = source.getVersion();
if (destVersion < srcVersion)
{
destination.setVersion(srcVersion);
}
int pageIndexOpenActionDest = -1;
if (destCatalog.getOpenAction() == null)
{
// PDFBOX-3972: get local dest page index, it must be reassigned after the page cloning
PDDestinationOrAction openAction = null;
try
{
openAction = srcCatalog.getOpenAction();
}
catch (IOException ex)
{
// PDFBOX-4223
LOG.error("Invalid OpenAction ignored", ex);
}
PDDestination openActionDestination = null;
if (openAction instanceof PDActionGoTo)
{
openActionDestination = ((PDActionGoTo) openAction).getDestination();
}
else if (openAction instanceof PDDestination)
{
openActionDestination = (PDDestination) openAction;
}
// note that it can also be something else, e.g. PDActionJavaScript, then do nothing
if (openActionDestination instanceof PDPageDestination)
{
PDPage page = ((PDPageDestination) openActionDestination).getPage();
if (page != null)
{
pageIndexOpenActionDest = srcCatalog.getPages().indexOf(page);
}
}
destCatalog.setOpenAction(openAction);
}
PDFCloneUtility cloner = new PDFCloneUtility(destination);
mergeAcroForm(cloner, destCatalog, srcCatalog);
COSArray destThreads = (COSArray) destCatalog.getCOSObject().getDictionaryObject(COSName.THREADS);
COSArray srcThreads = (COSArray) cloner.cloneForNewDocument(destCatalog.getCOSObject().getDictionaryObject(
COSName.THREADS));
if (destThreads == null)
{
destCatalog.getCOSObject().setItem(COSName.THREADS, srcThreads);
}
else
{
destThreads.addAll(srcThreads);
}
PDDocumentNameDictionary destNames = destCatalog.getNames();
PDDocumentNameDictionary srcNames = srcCatalog.getNames();
if (srcNames != null)
{
if (destNames == null)
{
destCatalog.getCOSObject().setItem(COSName.NAMES, cloner.cloneForNewDocument(srcNames));
}
else
{
cloner.cloneMerge(srcNames, destNames);
}
}
if (destNames != null && destNames.getCOSObject().containsKey(COSName.ID_TREE))
{
// found in 001031.pdf from PDFBOX-4417 and doesn't belong there
destNames.getCOSObject().removeItem(COSName.ID_TREE);
LOG.warn("Removed /IDTree from /Names dictionary, doesn't belong there");
}
PDDocumentNameDestinationDictionary destDests = destCatalog.getDests();
PDDocumentNameDestinationDictionary srcDests = srcCatalog.getDests();
if (srcDests != null)
{
if (destDests == null)
{
destCatalog.getCOSObject().setItem(COSName.DESTS, cloner.cloneForNewDocument(srcDests));
}
else
{
cloner.cloneMerge(srcDests, destDests);
}
}
PDDocumentOutline destOutline = destCatalog.getDocumentOutline();
PDDocumentOutline srcOutline = srcCatalog.getDocumentOutline();
if (srcOutline != null)
{
if (destOutline == null || destOutline.getFirstChild() == null)
{
PDDocumentOutline cloned = new PDDocumentOutline((COSDictionary) cloner.cloneForNewDocument(srcOutline));
destCatalog.setDocumentOutline(cloned);
}
else
{
// search last sibling for dest, because /Last entry is sometimes wrong
PDOutlineItem destLastOutlineItem = destOutline.getFirstChild();
while (destLastOutlineItem.getNextSibling() != null)
{
destLastOutlineItem = destLastOutlineItem.getNextSibling();
}
for (PDOutlineItem item : srcOutline.children())
{
// get each child, clone its dictionary, remove siblings info,
// append outline item created from there
COSDictionary clonedDict = (COSDictionary) cloner.cloneForNewDocument(item);
clonedDict.removeItem(COSName.PREV);
clonedDict.removeItem(COSName.NEXT);
PDOutlineItem clonedItem = new PDOutlineItem(clonedDict);
destLastOutlineItem.insertSiblingAfter(clonedItem);
destLastOutlineItem = destLastOutlineItem.getNextSibling();
}
}
}
PageMode destPageMode = destCatalog.getPageMode();
PageMode srcPageMode = srcCatalog.getPageMode();
if (destPageMode == null)
{
destCatalog.setPageMode(srcPageMode);
}
COSDictionary destLabels = destCatalog.getCOSObject().getCOSDictionary(COSName.PAGE_LABELS);
COSDictionary srcLabels = srcCatalog.getCOSObject().getCOSDictionary(COSName.PAGE_LABELS);
if (srcLabels != null)
{
int destPageCount = destination.getNumberOfPages();
COSArray destNums;
if (destLabels == null)
{
destLabels = new COSDictionary();
destNums = new COSArray();
destLabels.setItem(COSName.NUMS, destNums);
destCatalog.getCOSObject().setItem(COSName.PAGE_LABELS, destLabels);
}
else
{
destNums = (COSArray) destLabels.getDictionaryObject(COSName.NUMS);
}
COSArray srcNums = (COSArray) srcLabels.getDictionaryObject(COSName.NUMS);
if (srcNums != null)
{
int startSize = destNums.size();
for (int i = 0; i < srcNums.size(); i += 2)
{
COSBase base = srcNums.getObject(i);
if (!(base instanceof COSNumber))
{
LOG.error("page labels ignored, index " + i + " should be a number, but is " + base);
// remove what we added
while (destNums.size() > startSize)
{
destNums.remove(startSize);
}
break;
}
COSNumber labelIndex = (COSNumber) base;
long labelIndexValue = labelIndex.intValue();
destNums.add(COSInteger.get(labelIndexValue + destPageCount));
destNums.add(cloner.cloneForNewDocument(srcNums.getObject(i + 1)));
}
}
}
COSStream destMetadata = destCatalog.getCOSObject().getCOSStream(COSName.METADATA);
COSStream srcMetadata = srcCatalog.getCOSObject().getCOSStream(COSName.METADATA);
if (destMetadata == null && srcMetadata != null)
{
try
{
PDStream newStream = new PDStream(destination, srcMetadata.createInputStream(), (COSName) null);
mergeInto(srcMetadata, newStream.getCOSObject(),
new HashSet<>(Arrays.asList(COSName.FILTER, COSName.LENGTH)));
destCatalog.getCOSObject().setItem(COSName.METADATA, newStream);
}
catch (IOException ex)
{
// PDFBOX-4227 cleartext XMP stream with /Flate
LOG.error("Metadata skipped because it could not be read", ex);
}
}
COSDictionary destOCP = destCatalog.getCOSObject().getCOSDictionary(COSName.OCPROPERTIES);
COSDictionary srcOCP = srcCatalog.getCOSObject().getCOSDictionary(COSName.OCPROPERTIES);
if (destOCP == null && srcOCP != null)
{
destCatalog.getCOSObject().setItem(COSName.OCPROPERTIES, cloner.cloneForNewDocument(srcOCP));
}
else if (destOCP != null && srcOCP != null)
{
cloner.cloneMerge(srcOCP, destOCP);
}
mergeOutputIntents(cloner, srcCatalog, destCatalog);
// merge logical structure hierarchy
boolean mergeStructTree = false;
int destParentTreeNextKey = -1;
Map<Integer, COSObjectable> srcNumberTreeAsMap = null;
Map<Integer, COSObjectable> destNumberTreeAsMap = null;
PDStructureTreeRoot srcStructTree = srcCatalog.getStructureTreeRoot();
PDStructureTreeRoot destStructTree = destCatalog.getStructureTreeRoot();
if (destStructTree == null && srcStructTree != null)
{
// create a dummy structure tree in the destination, so that the source
// tree is cloned. (We can't just copy the tree reference due to PDFBOX-3999)
destStructTree = new PDStructureTreeRoot();
destCatalog.setStructureTreeRoot(destStructTree);
destStructTree.setParentTree(new PDNumberTreeNode(PDParentTreeValue.class));
// PDFBOX-4429: remove bogus StructParent(s)
for (PDPage page : destCatalog.getPages())
{
page.getCOSObject().removeItem(COSName.STRUCT_PARENTS);
for (PDAnnotation ann : page.getAnnotations())
{
ann.getCOSObject().removeItem(COSName.STRUCT_PARENT);
}
}
}
if (destStructTree != null)
{
PDNumberTreeNode destParentTree = destStructTree.getParentTree();
destParentTreeNextKey = destStructTree.getParentTreeNextKey();
if (destParentTree != null)
{
destNumberTreeAsMap = getNumberTreeAsMap(destParentTree);
if (destParentTreeNextKey < 0)
{
if (destNumberTreeAsMap.isEmpty())
{
destParentTreeNextKey = 0;
}
else
{
destParentTreeNextKey = Collections.max(destNumberTreeAsMap.keySet()) + 1;
}
}
if (destParentTreeNextKey >= 0 && srcStructTree != null)
{
PDNumberTreeNode srcParentTree = srcStructTree.getParentTree();
if (srcParentTree != null)
{
srcNumberTreeAsMap = getNumberTreeAsMap(srcParentTree);
if (!srcNumberTreeAsMap.isEmpty())
{
mergeStructTree = true;
}
}
}
}
}
Map<COSDictionary, COSDictionary> objMapping = new HashMap<>();
int pageIndex = 0;
for (PDPage page : srcCatalog.getPages())
{
PDPage newPage = new PDPage((COSDictionary) cloner.cloneForNewDocument(page.getCOSObject()));
if (!mergeStructTree)
{
// PDFBOX-4429: remove bogus StructParent(s)
newPage.getCOSObject().removeItem(COSName.STRUCT_PARENTS);
for (PDAnnotation ann : newPage.getAnnotations())
{
ann.getCOSObject().removeItem(COSName.STRUCT_PARENT);
}
}
newPage.setCropBox(page.getCropBox());
newPage.setMediaBox(page.getMediaBox());
newPage.setRotation(page.getRotation());
PDResources resources = page.getResources();
if (resources != null)
{
// this is smart enough to just create references for resources that are used on multiple pages
newPage.setResources(new PDResources((COSDictionary) cloner.cloneForNewDocument(resources)));
}
else
{
newPage.setResources(new PDResources());
}
if (mergeStructTree)
{
// add the value of the destination ParentTreeNextKey to every source element
// StructParent(s) value so that these don't overlap with the existing values
updateStructParentEntries(newPage, destParentTreeNextKey);
objMapping.put(page.getCOSObject(), newPage.getCOSObject());
List<PDAnnotation> oldAnnots = page.getAnnotations();
List<PDAnnotation> newAnnots = newPage.getAnnotations();
for (int i = 0; i < oldAnnots.size(); i++)
{
objMapping.put(oldAnnots.get(i).getCOSObject(), newAnnots.get(i).getCOSObject());
}
// TODO update mapping for XObjects
}
destination.addPage(newPage);
if (pageIndex == pageIndexOpenActionDest)
{
// PDFBOX-3972: reassign the page.
// The openAction is either a PDActionGoTo or a PDPageDestination
PDDestinationOrAction openAction = destCatalog.getOpenAction();
PDPageDestination pageDestination;
if (openAction instanceof PDActionGoTo)
{
pageDestination = (PDPageDestination) ((PDActionGoTo) openAction).getDestination();
}
else
{
pageDestination = (PDPageDestination) openAction;
}
pageDestination.setPage(newPage);
}
++pageIndex;
}
if (mergeStructTree)
{
updatePageReferences(cloner, srcNumberTreeAsMap, objMapping);
int maxSrcKey = -1;
for (Map.Entry<Integer, COSObjectable> entry : srcNumberTreeAsMap.entrySet())
{
int srcKey = entry.getKey();
maxSrcKey = Math.max(srcKey, maxSrcKey);
destNumberTreeAsMap.put(destParentTreeNextKey + srcKey, cloner.cloneForNewDocument(entry.getValue()));
}
destParentTreeNextKey += maxSrcKey + 1;
PDNumberTreeNode newParentTreeNode = new PDNumberTreeNode(PDParentTreeValue.class);
// Note that all elements are stored flatly. This could become a problem for large files
// when these are opened in a viewer that uses the tagging information.
// If this happens, then PDNumberTreeNode should be improved with a convenience method that
// stores the map into a B+Tree, see https://en.wikipedia.org/wiki/B+_tree
newParentTreeNode.setNumbers(destNumberTreeAsMap);
destStructTree.setParentTree(newParentTreeNode);
destStructTree.setParentTreeNextKey(destParentTreeNextKey);
mergeKEntries(cloner, srcStructTree, destStructTree);
mergeRoleMap(srcStructTree, destStructTree);
mergeIDTree(cloner, srcStructTree, destStructTree);
mergeMarkInfo(destCatalog, srcCatalog);
mergeLanguage(destCatalog, srcCatalog);
mergeViewerPreferences(destCatalog, srcCatalog);
}
}
private void mergeViewerPreferences(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
PDViewerPreferences srcViewerPreferences = srcCatalog.getViewerPreferences();
if (srcViewerPreferences == null)
{
return;
}
PDViewerPreferences destViewerPreferences = destCatalog.getViewerPreferences();
if (destViewerPreferences == null)
{
destViewerPreferences = new PDViewerPreferences(new COSDictionary());
destCatalog.setViewerPreferences(destViewerPreferences);
}
mergeInto(srcViewerPreferences.getCOSObject(), destViewerPreferences.getCOSObject(),
Collections.<COSName>emptySet());
// check the booleans - set to true if one is set and true
if (srcViewerPreferences.hideToolbar() || destViewerPreferences.hideToolbar())
{
destViewerPreferences.setHideToolbar(true);
}
if (srcViewerPreferences.hideMenubar() || destViewerPreferences.hideMenubar())
{
destViewerPreferences.setHideMenubar(true);
}
if (srcViewerPreferences.hideWindowUI() || destViewerPreferences.hideWindowUI())
{
destViewerPreferences.setHideWindowUI(true);
}
if (srcViewerPreferences.fitWindow() || destViewerPreferences.fitWindow())
{
destViewerPreferences.setFitWindow(true);
}
if (srcViewerPreferences.centerWindow() || destViewerPreferences.centerWindow())
{
destViewerPreferences.setCenterWindow(true);
}
if (srcViewerPreferences.displayDocTitle() || destViewerPreferences.displayDocTitle())
{
destViewerPreferences.setDisplayDocTitle(true);
}
}
private void mergeLanguage(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
if (destCatalog.getLanguage() == null && srcCatalog.getLanguage() != null)
{
destCatalog.setLanguage(srcCatalog.getLanguage());
}
}
private void mergeMarkInfo(PDDocumentCatalog destCatalog, PDDocumentCatalog srcCatalog)
{
PDMarkInfo destMark = destCatalog.getMarkInfo();
PDMarkInfo srcMark = srcCatalog.getMarkInfo();
if (destMark == null)
{
destMark = new PDMarkInfo();
}
if (srcMark == null)
{
srcMark = new PDMarkInfo();
}
destMark.setMarked(true);
destMark.setSuspect(srcMark.isSuspect() || destMark.isSuspect());
destMark.setSuspect(srcMark.usesUserProperties() || destMark.usesUserProperties());
destCatalog.setMarkInfo(destMark);
}
private void mergeKEntries(PDFCloneUtility cloner,
PDStructureTreeRoot srcStructTree,
PDStructureTreeRoot destStructTree) throws IOException
{
// make new /K with array that has the input /K entries
COSArray newKArray = new COSArray();
if (destStructTree.getK() != null)
{
COSBase base = destStructTree.getK();
if (base instanceof COSArray)
{
newKArray.addAll((COSArray) base);
}
else
{
newKArray.add(base);
}
}
if (srcStructTree.getK() != null)
{
COSBase base = cloner.cloneForNewDocument(srcStructTree.getK());
if (base instanceof COSArray)
{
newKArray.addAll((COSArray) base);
}
else
{
newKArray.add(base);
}
}
if (newKArray.size() > 0)
{
COSDictionary kDictLevel0 = new COSDictionary();
updateParentEntry(newKArray, kDictLevel0);
kDictLevel0.setItem(COSName.K, newKArray);
kDictLevel0.setItem(COSName.P, destStructTree);
kDictLevel0.setItem(COSName.S, COSName.DOCUMENT);
destStructTree.setK(kDictLevel0);
}
}
private void mergeIDTree(PDFCloneUtility cloner,
PDStructureTreeRoot srcStructTree,
PDStructureTreeRoot destStructTree) throws IOException
{
PDNameTreeNode<PDStructureElement> srcIDTree = srcStructTree.getIDTree();
PDNameTreeNode<PDStructureElement> destIDTree = destStructTree.getIDTree();
if (srcIDTree == null)
{
return;
}
if (destIDTree == null)
{
destIDTree = new PDStructureElementNameTreeNode();
}
Map<String, PDStructureElement> srcNames = getIDTreeAsMap(srcIDTree);
Map<String, PDStructureElement> destNames = getIDTreeAsMap(destIDTree);
for (Map.Entry<String, PDStructureElement> entry : srcNames.entrySet())
{
if (destNames.containsKey(entry.getKey()))
{
LOG.warn("key " + entry.getKey() + " already exists in destination IDTree");
}
else
{
destNames.put(entry.getKey(),
new PDStructureElement((COSDictionary) cloner.cloneForNewDocument(entry.getValue().getCOSObject())));
}
}
destIDTree = new PDStructureElementNameTreeNode();
destIDTree.setNames(destNames);
destStructTree.setIDTree(destIDTree);
// Note that all elements are stored flatly. This could become a problem for large files
// when these are opened in a viewer that uses the tagging information.
// If this happens, then PDNameTreeNode should be improved with a convenience method that
// stores the map into a B+Tree, see https://en.wikipedia.org/wiki/B+_tree
}
// PDNameTreeNode.getNames() only brings one level, this is why we need this
// might be made public at a later time, or integrated into PDNameTreeNode with template.
static Map<String, PDStructureElement> getIDTreeAsMap(PDNameTreeNode<PDStructureElement> idTree)
throws IOException
{
Map<String, PDStructureElement> names = idTree.getNames();
if (names == null)
{
names = new LinkedHashMap<>();
}
else
{
// must copy because the map is read only
names = new LinkedHashMap<>(names);
}
List<PDNameTreeNode<PDStructureElement>> kids = idTree.getKids();
if (kids != null)
{
for (PDNameTreeNode<PDStructureElement> kid : kids)
{
names.putAll(getIDTreeAsMap(kid));
}
}
return names;
}
// PDNumberTreeNode.getNumbers() only brings one level, this is why we need this
// might be made public at a later time, or integrated into PDNumberTreeNode.
static Map<Integer, COSObjectable> getNumberTreeAsMap(PDNumberTreeNode tree)
throws IOException
{
Map<Integer, COSObjectable> numbers = tree.getNumbers();
if (numbers == null)
{
numbers = new LinkedHashMap<>();
}
else
{
// must copy because the map is read only
numbers = new LinkedHashMap<>(numbers);
}
List<PDNumberTreeNode> kids = tree.getKids();
if (kids != null)
{
for (PDNumberTreeNode kid : kids)
{
numbers.putAll(getNumberTreeAsMap(kid));
}
}
return numbers;
}
private void mergeRoleMap(PDStructureTreeRoot srcStructTree, PDStructureTreeRoot destStructTree)
{
COSDictionary srcDict = srcStructTree.getCOSObject().getCOSDictionary(COSName.ROLE_MAP);
COSDictionary destDict = destStructTree.getCOSObject().getCOSDictionary(COSName.ROLE_MAP);
if (srcDict == null)
{
return;
}
if (destDict == null)
{
destStructTree.getCOSObject().setItem(COSName.ROLE_MAP, srcDict); // clone not needed
return;
}
for (Map.Entry<COSName, COSBase> entry : srcDict.entrySet())
{
COSBase destValue = destDict.getDictionaryObject(entry.getKey());
if (destValue != null && destValue.equals(entry.getValue()))
{
// already exists, but identical
continue;
}
if (destDict.containsKey(entry.getKey()))
{
LOG.warn("key " + entry.getKey() + " already exists in destination RoleMap");
}
else
{
destDict.setItem(entry.getKey(), entry.getValue());
}
}
}
private void mergeAcroForm(PDFCloneUtility cloner, PDDocumentCatalog destCatalog,
PDDocumentCatalog srcCatalog ) throws IOException
{
try
{
PDAcroForm destAcroForm = destCatalog.getAcroForm();
PDAcroForm srcAcroForm = srcCatalog.getAcroForm();
if (destAcroForm == null && srcAcroForm != null)
{
destCatalog.getCOSObject().setItem(COSName.ACRO_FORM,
cloner.cloneForNewDocument(srcAcroForm.getCOSObject()));
}
else
{
if (srcAcroForm != null)
{
if (acroFormMergeMode == AcroFormMergeMode.PDFBOX_LEGACY_MODE)
{
acroFormLegacyMode(cloner, destAcroForm, srcAcroForm);
}
else if (acroFormMergeMode == AcroFormMergeMode.JOIN_FORM_FIELDS_MODE)
{
acroFormJoinFieldsMode(cloner, destAcroForm, srcAcroForm);
}
}
}
}
catch (IOException e)
{
// if we are not ignoring exceptions, we'll re-throw this
if (!ignoreAcroFormErrors)
{
throw new IOException(e);
}
}
}
/*
* Merge the contents of the source form into the destination form for the
* destination file.
*
* @param cloner the object cloner for the destination document
* @param destAcroForm the destination form
* @param srcAcroForm the source form
* @throws IOException If an error occurs while adding the field.
*/
private void acroFormJoinFieldsMode(PDFCloneUtility cloner, PDAcroForm destAcroForm, PDAcroForm srcAcroForm)
throws IOException
{
acroFormLegacyMode(cloner, destAcroForm, srcAcroForm);
}
/*
* Merge the contents of the source form into the destination form for the
* destination file.
*
* @param cloner the object cloner for the destination document
* @param destAcroForm the destination form
* @param srcAcroForm the source form
* @throws IOException If an error occurs while adding the field.
*/
private void acroFormLegacyMode(PDFCloneUtility cloner, PDAcroForm destAcroForm, PDAcroForm srcAcroForm)
throws IOException
{
List<PDField> srcFields = srcAcroForm.getFields();
COSArray destFields;
if (srcFields != null && !srcFields.isEmpty())
{
// if a form is merged multiple times using PDFBox the newly generated
// fields starting with dummyFieldName may already exist. We need to determine the last unique
// number used and increment that.
final String prefix = "dummyFieldName";
final int prefixLength = prefix.length();
for (PDField destField : destAcroForm.getFieldTree())
{
String fieldName = destField.getPartialName();
if (fieldName.startsWith(prefix))
{
nextFieldNum = Math.max(nextFieldNum, Integer.parseInt(fieldName.substring(prefixLength, fieldName.length())) + 1);
}
}
// get the destinations root fields. Could be that the entry doesn't exist
// or is of wrong type
COSBase base = destAcroForm.getCOSObject().getItem(COSName.FIELDS);
if (base instanceof COSArray)
{
destFields = (COSArray) base;
}
else
{
destFields = new COSArray();
}
for (PDField srcField : srcAcroForm.getFields())
{
COSDictionary dstField = (COSDictionary) cloner.cloneForNewDocument(srcField.getCOSObject());
// if the form already has a field with this name then we need to rename this field
// to prevent merge conflicts.
if (destAcroForm.getField(srcField.getFullyQualifiedName()) != null)
{
dstField.setString(COSName.T, prefix + nextFieldNum++);
}
destFields.add(dstField);
}
destAcroForm.getCOSObject().setItem(COSName.FIELDS,destFields);
}
}
// copy outputIntents to destination, but avoid duplicate OutputConditionIdentifier,
// except when it is missing or is named "Custom".
private void mergeOutputIntents(PDFCloneUtility cloner,
PDDocumentCatalog srcCatalog, PDDocumentCatalog destCatalog) throws IOException
{
List<PDOutputIntent> srcOutputIntents = srcCatalog.getOutputIntents();
List<PDOutputIntent> dstOutputIntents = destCatalog.getOutputIntents();
for (PDOutputIntent srcOI : srcOutputIntents)
{
String srcOCI = srcOI.getOutputConditionIdentifier();
if (srcOCI != null && !"Custom".equals(srcOCI))
{
// is that identifier already there?
boolean skip = false;
for (PDOutputIntent dstOI : dstOutputIntents)
{
if (dstOI.getOutputConditionIdentifier().equals(srcOCI))
{
skip = true;
break;
}
}
if (skip)
{
continue;
}
}
destCatalog.addOutputIntent(new PDOutputIntent((COSDictionary) cloner.cloneForNewDocument(srcOI)));
dstOutputIntents.add(srcOI);
}
}
private int nextFieldNum = 1;
/**
* Indicates if acroform errors are ignored or not.
*
* @return true if acroform errors are ignored
*/
public boolean isIgnoreAcroFormErrors()
{
return ignoreAcroFormErrors;
}
/**
* Set to true to ignore acroform errors.
*
* @param ignoreAcroFormErrorsValue true if acroform errors should be
* ignored
*/
public void setIgnoreAcroFormErrors(boolean ignoreAcroFormErrorsValue)
{
ignoreAcroFormErrors = ignoreAcroFormErrorsValue;
}
/**
* Update the Pg and Obj references to the new (merged) page.
*/
private void updatePageReferences(PDFCloneUtility cloner,
Map<Integer, COSObjectable> numberTreeAsMap,
Map<COSDictionary, COSDictionary> objMapping) throws IOException
{
for (COSObjectable obj : numberTreeAsMap.values())
{
if (obj == null)
{
continue;
}
PDParentTreeValue val = (PDParentTreeValue) obj;
COSBase base = val.getCOSObject();
if (base instanceof COSArray)
{
updatePageReferences(cloner, (COSArray) base, objMapping);
}
else
{
updatePageReferences(cloner, (COSDictionary) base, objMapping);
}
}
}
/**
* Update the Pg and Obj references to the new (merged) page.
*
* @param parentTreeEntry
* @param objMapping mapping between old and new references
*/
private void updatePageReferences(PDFCloneUtility cloner,
COSDictionary parentTreeEntry, Map<COSDictionary, COSDictionary> objMapping)
throws IOException
{
COSDictionary pageDict = parentTreeEntry.getCOSDictionary(COSName.PG);
if (objMapping.containsKey(pageDict))
{
parentTreeEntry.setItem(COSName.PG, objMapping.get(pageDict));
}
COSBase obj = parentTreeEntry.getDictionaryObject(COSName.OBJ);
if (obj instanceof COSDictionary)
{
COSDictionary objDict = (COSDictionary) obj;
if (objMapping.containsKey(objDict))
{
parentTreeEntry.setItem(COSName.OBJ, objMapping.get(objDict));
}
else
{
// PDFBOX-3999: clone objects that are not in mapping to make sure that
// these don't remain attached to the source document
COSBase item = parentTreeEntry.getItem(COSName.OBJ);
if (item instanceof COSObject)
{
LOG.debug("clone potential orphan object in structure tree: " + item +
", Type: " + objDict.getNameAsString(COSName.TYPE) +
", Subtype: " + objDict.getNameAsString(COSName.SUBTYPE) +
", T: " + objDict.getNameAsString(COSName.T));
}
else
{
// don't display in full because of stack overflow
LOG.debug("clone potential orphan object in structure tree" +
", Type: " + objDict.getNameAsString(COSName.TYPE) +
", Subtype: " + objDict.getNameAsString(COSName.SUBTYPE) +
", T: " + objDict.getNameAsString(COSName.T));
}
parentTreeEntry.setItem(COSName.OBJ, cloner.cloneForNewDocument(obj));
}
}
COSBase kSubEntry = parentTreeEntry.getDictionaryObject(COSName.K);
if (kSubEntry instanceof COSArray)
{
updatePageReferences(cloner, (COSArray) kSubEntry, objMapping);
}
else if (kSubEntry instanceof COSDictionary)
{
updatePageReferences(cloner, (COSDictionary) kSubEntry, objMapping);
}
}
private void updatePageReferences(PDFCloneUtility cloner,
COSArray parentTreeEntry, Map<COSDictionary, COSDictionary> objMapping)
throws IOException
{
for (int i = 0; i < parentTreeEntry.size(); i++)
{
COSBase subEntry = parentTreeEntry.getObject(i);
if (subEntry instanceof COSArray)
{
updatePageReferences(cloner, (COSArray) subEntry, objMapping);
}
else if (subEntry instanceof COSDictionary)
{
updatePageReferences(cloner, (COSDictionary) subEntry, objMapping);
}
}
}
/**
* Update the P reference to the new parent dictionary.
*
* @param kArray the kids array
* @param newParent the new parent
*/
private void updateParentEntry(COSArray kArray, COSDictionary newParent)
{
for (int i = 0; i < kArray.size(); i++)
{
COSBase subEntry = kArray.getObject(i);
if (subEntry instanceof COSDictionary)
{
COSDictionary dictEntry = (COSDictionary) subEntry;
if (dictEntry.getDictionaryObject(COSName.P) != null)
{
dictEntry.setItem(COSName.P, newParent);
}
}
}
}
/**
* Update the StructParents and StructParent values in a PDPage.
*
* @param page the new page
* @param structParentOffset the offset which should be applied
*/
private void updateStructParentEntries(PDPage page, int structParentOffset) throws IOException
{
if (page.getStructParents() >= 0)
{
page.setStructParents(page.getStructParents() + structParentOffset);
}
List<PDAnnotation> annots = page.getAnnotations();
List<PDAnnotation> newannots = new ArrayList<>();
for (PDAnnotation annot : annots)
{
if (annot.getStructParent() >= 0)
{
annot.setStructParent(annot.getStructParent() + structParentOffset);
}
newannots.add(annot);
}
page.setAnnotations(newannots);
}
/**
* Test for dynamic XFA content.
*
* @param acroForm the AcroForm
* @return true if there is a dynamic XFA form.
*/
private boolean isDynamicXfa(PDAcroForm acroForm)
{
return acroForm != null && acroForm.xfaIsDynamic();
}
/**
* This will add all of the dictionaries keys/values to this dictionary, but
* only if they are not in an exclusion list and if they don't already
* exist. If a key already exists in this dictionary then nothing is
* changed.
*
* @param src The source dictionary to get the keys/values from.
* @param dst The destination dictionary to merge the keys/values into.
* @param exclude Names of keys that shall be skipped.
*/
private void mergeInto(COSDictionary src, COSDictionary dst, Set<COSName> exclude)
{
for (Map.Entry<COSName, COSBase> entry : src.entrySet())
{
if (!exclude.contains(entry.getKey()) && !dst.containsKey(entry.getKey()))
{
dst.setItem(entry.getKey(), entry.getValue());
}
}
}
}
| PDFBOX-4892: set individual initial ArrayList size, as suggested by valerybokov
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1887273 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/multipdf/PDFMergerUtility.java | PDFBOX-4892: set individual initial ArrayList size, as suggested by valerybokov | <ide><path>dfbox/src/main/java/org/apache/pdfbox/multipdf/PDFMergerUtility.java
<ide> // - all FileInputStreams are closed
<ide> // - there's a way to see which errors occurred
<ide>
<del> List<PDDocument> tobeclosed = new ArrayList<>();
<add> List<PDDocument> tobeclosed = new ArrayList<>(sources.size());
<ide> MemoryUsageSetting partitionedMemSetting = memUsageSetting != null ?
<ide> memUsageSetting.getPartitionedCopy(sources.size()+1) :
<ide> MemoryUsageSetting.setupMainMemoryOnly(); |
|
Java | apache-2.0 | bcd358b7569c1ee7fafb4c91f473c08a0d218eda | 0 | argv0/cloudstack,DaanHoogland/cloudstack,argv0/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,argv0/cloudstack,cinderella/incubator-cloudstack,resmo/cloudstack,cinderella/incubator-cloudstack,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,mufaddalq/cloudstack-datera-driver,cinderella/incubator-cloudstack,resmo/cloudstack,cinderella/incubator-cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,wido/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,resmo/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,cinderella/incubator-cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack,wido/cloudstack,jcshen007/cloudstack,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,argv0/cloudstack,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,argv0/cloudstack,DaanHoogland/cloudstack,argv0/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,mufaddalq/cloudstack-datera-driver | /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.cloud.agent.AgentManager;
import com.cloud.consoleproxy.ConsoleProxyManager;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.NetworkManager;
import com.cloud.network.router.VirtualNetworkApplianceManager;
import com.cloud.server.ManagementServer;
import com.cloud.storage.StorageManager;
import com.cloud.storage.allocator.StoragePoolAllocator;
import com.cloud.storage.secondary.SecondaryStorageVmManager;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.vm.UserVmManager;
public enum Config {
// Alert
AlertEmailAddresses("Alert", ManagementServer.class, String.class, "alert.email.addresses", null, "Comma separated list of email addresses used for sending alerts.", null),
AlertEmailSender("Alert", ManagementServer.class, String.class, "alert.email.sender", null, "Sender of alert email (will be in the From header of the email).", null),
AlertSMTPHost("Alert", ManagementServer.class, String.class, "alert.smtp.host", null, "SMTP hostname used for sending out email alerts.", null),
AlertSMTPPassword("Alert", ManagementServer.class, String.class, "alert.smtp.password", null, "Password for SMTP authentication (applies only if alert.smtp.useAuth is true).", null),
AlertSMTPPort("Alert", ManagementServer.class, Integer.class, "alert.smtp.port", "465", "Port the SMTP server is listening on.", null),
AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null),
AlertSMTPUsername("Alert", ManagementServer.class, String.class, "alert.smtp.username", null, "Username for SMTP authentication (applies only if alert.smtp.useAuth is true).", null),
AlertWait("Alert", AgentManager.class, Integer.class, "alert.wait", null, "Seconds to wait before alerting on a disconnected agent", null),
// Storage
StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null),
StorageStatsInterval("Storage", ManagementServer.class, String.class, "storage.stats.interval", "60000", "The interval (in milliseconds) when storage stats (per host) are retrieved from agents.", null),
MaxVolumeSize("Storage", ManagementServer.class, Integer.class, "storage.max.volume.size", "2000", "The maximum size for a volume (in GB).", null),
TotalRetries("Storage", AgentManager.class, Integer.class, "total.retries", "4", "The number of times each command sent to a host should be retried in case of failure.", null),
// Network
GuestVlanBits("Network", ManagementServer.class, Integer.class, "guest.vlan.bits", "12", "The number of bits to reserve for the VLAN identifier in the guest subnet.", null),
//MulticastThrottlingRate("Network", ManagementServer.class, Integer.class, "multicast.throttling.rate", "10", "Default multicast rate in megabits per second allowed.", null),
NetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in network.", null),
GuestDomainSuffix("Network", AgentManager.class, String.class, "guest.domain.suffix", "cloud.internal", "Default domain name for vms inside virtualized networks fronted by router", null),
DirectNetworkNoDefaultRoute("Network", ManagementServer.class, Boolean.class, "direct.network.no.default.route", "false", "Direct Network Dhcp Server should not send a default route", "true/false"),
OvsNetwork("Network", ManagementServer.class, Boolean.class, "open.vswitch.vlan.network", "false", "enable/disable vlan remapping of open vswitch network", null),
OvsTunnelNetwork("Network", ManagementServer.class, Boolean.class, "open.vswitch.tunnel.network", "false", "enable/disable open vswitch tunnel network(no vlan)", null),
VmNetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "vm.network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in User vm's default network.", null),
//VPN
RemoteAccessVpnPskLength("Network", AgentManager.class, Integer.class, "remote.access.vpn.psk.length", "24", "The length of the ipsec preshared key (minimum 8, maximum 256)", null),
RemoteAccessVpnClientIpRange("Network", AgentManager.class, String.class, "remote.access.vpn.client.iprange", "10.1.2.1-10.1.2.8", "The range of ips to be allocated to remote access vpn clients. The first ip in the range is used by the VPN server", null),
RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null),
// Usage
CapacityCheckPeriod("Usage", ManagementServer.class, Integer.class, "capacity.check.period", "300000", "The interval in milliseconds between capacity checks", null),
StorageAllocatedCapacityThreshold("Usage", ManagementServer.class, Float.class, "storage.allocated.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of allocated storage utilization above which alerts will be sent about low storage available.", null),
StorageCapacityThreshold("Usage", ManagementServer.class, Float.class, "storage.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available.", null),
CPUCapacityThreshold("Usage", ManagementServer.class, Float.class, "cpu.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of cpu utilization above which alerts will be sent about low cpu available.", null),
MemoryCapacityThreshold("Usage", ManagementServer.class, Float.class, "memory.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of memory utilization above which alerts will be sent about low memory available.", null),
PublicIpCapacityThreshold("Usage", ManagementServer.class, Float.class, "public.ip.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of public IP address space utilization above which alerts will be sent.", null),
PrivateIpCapacityThreshold("Usage", ManagementServer.class, Float.class, "private.ip.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of private IP address space utilization above which alerts will be sent.", null),
// Console Proxy
ConsoleProxyCapacityStandby("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacity.standby", "10", "The minimal number of console proxy viewer sessions that system is able to serve immediately(standby capacity)", null),
ConsoleProxyCapacityScanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacityscan.interval", "30000", "The time interval(in millisecond) to scan whether or not system needs more console proxy to ensure minimal standby capacity", null),
ConsoleProxyCmdPort("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.cmd.port", "8001", "Console proxy command port that is used to communicate with management server", null),
ConsoleProxyRestart("Console Proxy", AgentManager.class, Boolean.class, "consoleproxy.restart", "true", "Console proxy restart flag, defaulted to true", null),
ConsoleProxyUrlDomain("Console Proxy", AgentManager.class, String.class, "consoleproxy.url.domain", "realhostip.com", "Console proxy url domain", null),
ConsoleProxyLoadscanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.loadscan.interval", "10000", "The time interval(in milliseconds) to scan console proxy working-load info", null),
ConsoleProxyRamSize("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.ram.size", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE), "RAM size (in MB) used to create new console proxy VMs", null),
ConsoleProxyCpuMHz("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.cpu.mhz", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_VM_CPUMHZ), "CPU speed (in MHz) used to create new console proxy VMs", null),
ConsoleProxySessionMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.max", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_CAPACITY), "The max number of viewer sessions console proxy is configured to serve for", null),
ConsoleProxySessionTimeout("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.timeout", "300000", "Timeout(in milliseconds) that console proxy tries to maintain a viewer session before it times out the session for no activity", null),
ConsoleProxyDisableRpFilter("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.disable.rpfilter", "true", "disable rp_filter on console proxy VM public interface", null),
ConsoleProxyLaunchMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.launch.max", "10", "maximum number of console proxy instances per zone can be launched", null),
ConsoleProxyManagementState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(),
"console proxy service management state", null),
ConsoleProxyManagementLastState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state.last", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(),
"last console proxy service management state", null),
// Snapshots
SnapshotHourlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.hourly", "8", "Maximum hourly snapshots for a volume", null),
SnapshotDailyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.daily", "8", "Maximum daily snapshots for a volume", null),
SnapshotWeeklyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.weekly", "8", "Maximum weekly snapshots for a volume", null),
SnapshotMonthlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.monthly", "8", "Maximum monthly snapshots for a volume", null),
SnapshotPollInterval("Snapshots", SnapshotManager.class, Integer.class, "snapshot.poll.interval", "300", "The time interval in seconds when the management server polls for snapshots to be scheduled.", null),
SnapshotDeltaMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.delta.max", "16", "max delta snapshots between two full snapshots.", null),
// Advanced
JobExpireMinutes("Advanced", ManagementServer.class, String.class, "job.expire.minutes", "1440", "Time (in minutes) for async-jobs to be kept in system", null),
JobCancelThresholdMinutes("Advanced", ManagementServer.class, String.class, "job.cancel.threshold.minutes", "60", "Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", null),
AccountCleanupInterval("Advanced", ManagementServer.class, Integer.class, "account.cleanup.interval", "86400", "The interval (in seconds) between cleanup for removed accounts", null),
AllowPublicUserTemplates("Advanced", ManagementServer.class, Integer.class, "allow.public.user.templates", "true", "If false, users will not be able to create public templates.", null),
InstanceName("Advanced", AgentManager.class, String.class, "instance.name", "VM", "Name of the deployment instance.", null),
ExpungeDelay("Advanced", UserVmManager.class, Integer.class, "expunge.delay", "86400", "Determines how long (in seconds) to wait before actually expunging destroyed vm. The default value = the default value of expunge.interval", null),
ExpungeInterval("Advanced", UserVmManager.class, Integer.class, "expunge.interval", "86400", "The interval (in seconds) to wait before running the expunge thread.", null),
ExpungeWorkers("Advanced", UserVmManager.class, Integer.class, "expunge.workers", "1", "Number of workers performing expunge ", null),
ExtractURLCleanUpInterval("Advanced", ManagementServer.class, Integer.class, "extract.url.cleanup.interval", "120", "The interval (in seconds) to wait before cleaning up the extract URL's ", null),
HostStatsInterval("Advanced", ManagementServer.class, Integer.class, "host.stats.interval", "60000", "The interval (in milliseconds) when host stats are retrieved from agents.", null),
HostRetry("Advanced", AgentManager.class, Integer.class, "host.retry", "2", "Number of times to retry hosts for creating a volume", null),
IntegrationAPIPort("Advanced", ManagementServer.class, Integer.class, "integration.api.port", "8096", "Defaul API port", null),
InvestigateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "investigate.retry.interval", "60", "Time (in seconds) between VM pings when agent is disconnected", null),
MigrateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "migrate.retry.interval", "120", "Time (in seconds) between migration retries", null),
PingInterval("Advanced", AgentManager.class, Integer.class, "ping.interval", "60", "Ping interval in seconds", null),
PingTimeout("Advanced", AgentManager.class, Float.class, "ping.timeout", "2.5", "Multiplier to ping.interval before announcing an agent has timed out", null),
Port("Advanced", AgentManager.class, Integer.class, "port", "8250", "Port to listen on for agent connection.", null),
RouterCpuMHz("Advanced", NetworkManager.class, Integer.class, "router.cpu.mhz", String.valueOf(VirtualNetworkApplianceManager.DEFAULT_ROUTER_CPU_MHZ), "Default CPU speed (MHz) for router VM.", null),
RestartRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "restart.retry.interval", "600", "Time (in seconds) between retries to restart a vm", null),
RouterStatsInterval("Advanced", NetworkManager.class, Integer.class, "router.stats.interval", "300", "Interval (in seconds) to report router statistics.", null),
RouterTemplateId("Advanced", NetworkManager.class, Long.class, "router.template.id", "1", "Default ID for template.", null),
StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null),
StopRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "stop.retry.interval", "600", "Time in seconds between retries to stop or destroy a vm" , null),
StorageCleanupInterval("Advanced", StorageManager.class, Integer.class, "storage.cleanup.interval", "86400", "The interval (in seconds) to wait before running the storage cleanup thread.", null),
StorageCleanupEnabled("Advanced", StorageManager.class, Boolean.class, "storage.cleanup.enabled", "true", "Enables/disables the storage cleanup thread.", null),
UpdateWait("Advanced", AgentManager.class, Integer.class, "update.wait", "600", "Time to wait (in seconds) before alerting on a updating agent", null),
Wait("Advanced", AgentManager.class, Integer.class, "wait", "1800", "Time in seconds to wait for control commands to return", null),
XapiWait("Advanced", AgentManager.class, Integer.class, "xapiwait", "600", "Time (in seconds) to wait for XAPI to return", null),
CmdsWait("Advanced", AgentManager.class, Integer.class, "cmd.wait", "7200", "Time (in seconds) to wait for some heavy time-consuming commands", null),
Workers("Advanced", AgentManager.class, Integer.class, "workers", "5", "Number of worker threads.", null),
MountParent("Advanced", ManagementServer.class, String.class, "mount.parent", "/var/lib/cloud/mnt", "The mount point on the Management Server for Secondary Storage.", null),
// UpgradeURL("Advanced", ManagementServer.class, String.class, "upgrade.url", "http://example.com:8080/client/agent/update.zip", "The upgrade URL is the URL of the management server that agents will connect to in order to automatically upgrade.", null),
SystemVMUseLocalStorage("Advanced", ManagementServer.class, Boolean.class, "system.vm.use.local.storage", "false", "Indicates whether to use local storage pools or shared storage pools for system VMs.", null),
SystemVMAutoReserveCapacity("Advanced", ManagementServer.class, Boolean.class, "system.vm.auto.reserve.capacity", "true", "Indicates whether or not to automatically reserver system VM standby capacity.", null),
CPUOverprovisioningFactor("Advanced", ManagementServer.class, String.class, "cpu.overprovisioning.factor", "1", "Used for CPU overprovisioning calculation; available CPU will be (actualCpuCapacity * cpu.overprovisioning.factor)", null),
LinkLocalIpNums("Advanced", ManagementServer.class, Integer.class, "linkLocalIp.nums", "10", "The number of link local ip that needed by domR(in power of 2)", null),
HypervisorList("Advanced", ManagementServer.class, String.class, "hypervisor.list", HypervisorType.KVM + "," + HypervisorType.XenServer + "," + HypervisorType.VMware + "," + HypervisorType.BareMetal, "The list of hypervisors that this deployment will use.", "hypervisorList"),
ManagementHostIPAdr("Advanced", ManagementServer.class, String.class, "host", "localhost", "The ip address of management server", null),
ManagementNetwork("Advanced", ManagementServer.class, String.class, "management.network.cidr", null, "The cidr of management server network", null),
EventPurgeDelay("Advanced", ManagementServer.class, Integer.class, "event.purge.delay", "15", "Events older than specified number days will be purged. Set this value to 0 to never delete events", null),
UseLocalStorage("Premium", ManagementServer.class, Boolean.class, "use.local.storage", "false", "Should we use the local storage if it's available?", null),
SecStorageVmRamSize("Advanced", AgentManager.class, Integer.class, "secstorage.vm.ram.size", String.valueOf(SecondaryStorageVmManager.DEFAULT_SS_VM_RAMSIZE), "RAM size (in MB) used to create new secondary storage vms", null),
SecStorageVmCpuMHz("Advanced", AgentManager.class, Integer.class, "secstorage.vm.cpu.mhz", String.valueOf(SecondaryStorageVmManager.DEFAULT_SS_VM_CPUMHZ), "CPU speed (in MHz) used to create new secondary storage vms", null),
MaxTemplateAndIsoSize("Advanced", ManagementServer.class, Long.class, "max.template.iso.size", "50", "The maximum size for a downloaded template or ISO (in GB).", null),
SecStorageAllowedInternalDownloadSites("Advanced", ManagementServer.class, String.class, "secstorage.allowed.internal.sites", null, "Comma separated list of cidrs internal to the datacenter that can host template download servers", null),
SecStorageEncryptCopy("Advanced", ManagementServer.class, Boolean.class, "secstorage.encrypt.copy", "false", "Use SSL method used to encrypt copy traffic between zones", "true,false"),
SecStorageSecureCopyCert("Advanced", ManagementServer.class, String.class, "secstorage.ssl.cert.domain", "realhostip.com", "SSL certificate used to encrypt copy traffic between zones", null),
SecStorageCapacityStandby("Advanced", AgentManager.class, Integer.class, "secstorage.capacity.standby", "10", "The minimal number of command execution sessions that system is able to serve immediately(standby capacity)", null),
SecStorageSessionMax("Advanced", AgentManager.class, Integer.class, "secstorage.session.max", "50", "The max number of command execution sessions that a SSVM can handle", null),
SecStorageCmdExecutionTimeMax("Advanced", AgentManager.class, Integer.class, "secstorage.cmd.execution.time.max", "30", "The max command execution time in minute", null),
DirectAttachNetworkEnabled("Advanced", ManagementServer.class, Boolean.class, "direct.attach.network.externalIpAllocator.enabled", "false", "Direct-attach VMs using external DHCP server", "true,false"),
DirectAttachNetworkExternalAPIURL("Advanced", ManagementServer.class, String.class, "direct.attach.network.externalIpAllocator.url", null, "Direct-attach VMs using external DHCP server (API url)", null),
CheckPodCIDRs("Advanced", ManagementServer.class, String.class, "check.pod.cidrs", "true", "If true, different pods must belong to different CIDR subnets.", "true,false"),
NetworkGcWait("Advanced", ManagementServer.class, Integer.class, "network.gc.wait", "600", "Time (in seconds) to wait before shutting down a network that's not in used", null),
NetworkGcInterval("Advanced", ManagementServer.class, Integer.class, "network.gc.interval", "600", "Seconds to wait before checking for networks to shutdown", null),
HostCapacityCheckerWait("Advanced", ManagementServer.class, Integer.class, "host.capacity.checker.wait", "3600", "Time (in seconds) to wait before starting host capacity background checker", null),
HostCapacityCheckerInterval("Advanced", ManagementServer.class, Integer.class, "host.capacity.checker.interval", "3600", "Time (in seconds) to wait before recalculating host's capacity", null),
CapacitySkipcountingHours("Advanced", ManagementServer.class, Integer.class, "capacity.skipcounting.hours", "3600", "Time (in seconds) to wait before release VM's cpu and memory when VM in stopped state", null),
VmStatsInterval("Advanced", ManagementServer.class, Integer.class, "vm.stats.interval", "60000", "The interval (in milliseconds) when vm stats are retrieved from agents.", null),
VmTransitionWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.tranisition.wait.interval", "3600", "Time (in seconds) to wait before taking over a VM in transition state", null),
ControlCidr("Advanced", ManagementServer.class, String.class, "control.cidr", "169.254.0.0/16", "Changes the cidr for the control network traffic. Defaults to using link local. Must be unique within pods", null),
ControlGateway("Advanced", ManagementServer.class, String.class, "control.gateway", "169.254.0.1", "gateway for the control network traffic", null),
UseUserConcentratedPodAllocation("Advanced", ManagementServer.class, Boolean.class, "use.user.concentrated.pod.allocation", "true", "If true, deployment planner applies the user concentration heuristic during VM resource allocation", "true,false"),
HostCapacityTypeToOrderClusters("Advanced", ManagementServer.class, String.class, "host.capacityType.to.order.clusters", "CPU", "The host capacity type (CPU or RAM) is used by deployment planner to order clusters during VM resource allocation", "CPU,RAM"),
EndpointeUrl("Advanced", ManagementServer.class, String.class, "endpointe.url", "http://localhost:8080/client/api", "Endpointe Url", "The endpoint callback URL"),
// XenServer
VmAllocationAlgorithm("Advanced", ManagementServer.class, String.class, "vm.allocation.algorithm", "random", "If 'random', hosts within a pod will be randomly considered for VM/volume allocation. If 'firstfit', they will be considered on a first-fit basis.", null),
XenPublicNetwork("Network", ManagementServer.class, String.class, "xen.public.network.device", null, "[ONLY IF THE PUBLIC NETWORK IS ON A DEDICATED NIC]:The network name label of the physical device dedicated to the public network on a XenServer host", null),
XenStorageNetwork1("Network", ManagementServer.class, String.class, "xen.storage.network.device1", "cloud-stor1", "Specify when there are storage networks", null),
XenStorageNetwork2("Network", ManagementServer.class, String.class, "xen.storage.network.device2", "cloud-stor2", "Specify when there are storage networks", null),
XenPrivateNetwork("Network", ManagementServer.class, String.class, "xen.private.network.device", null, "Specify when the private network name is different", null),
NetworkGuestCidrLimit("Network", NetworkManager.class, Integer.class, "network.guest.cidr.limit", "22", "size limit for guest cidr; can't be less than this value", null),
XenMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.version", "3.3.1", "Minimum Xen version", null),
XenProductMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.product.version", "0.1.1", "Minimum XenServer version", null),
XenXapiMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.xapi.version", "1.3", "Minimum Xapi Tool Stack version", null),
XenMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.version", "3.4.2", "Maximum Xen version", null),
XenProductMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.product.version", "5.6.0", "Maximum XenServer version", null),
XenXapiMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.xapi.version", "1.3", "Maximum Xapi Tool Stack version", null),
XenSetupMultipath("Advanced", ManagementServer.class, String.class, "xen.setup.multipath", "false", "Setup the host to do multipath", null),
XenBondStorageNic("Advanced", ManagementServer.class, String.class, "xen.bond.storage.nics", null, "Attempt to bond the two networks if found", null),
XenHeartBeatInterval("Advanced", ManagementServer.class, Integer.class, "xen.heartbeat.interval", "60", "heartbeat to use when implementing XenServer Self Fencing", null),
XenGuestNetwork("Advanced", ManagementServer.class, String.class, "xen.guest.network.device", null, "Specify for guest network name label", null),
// VMware
VmwarePrivateNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.private.vswitch", null, "Specify the vSwitch on host for private network", null),
VmwarePublicNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.public.vswitch", null, "Specify the vSwitch on host for public network", null),
VmwareGuestNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.guest.vswitch", null, "Specify the vSwitch on host for guest network", null),
VmwareServiceConsole("Advanced", ManagementServer.class, String.class, "vmware.service.console", "Service Console", "Specify the service console network name (ESX host only)", null),
// KVM
KvmPublicNetwork("Advanced", ManagementServer.class, String.class, "kvm.public.network.device", null, "Specify the public bridge on host for public network", null),
KvmPrivateNetwork("Advanced", ManagementServer.class, String.class, "kvm.private.network.device", null, "Specify the private bridge on host for private network", null),
KvmGuestNetwork("Advanced", ManagementServer.class, String.class, "kvm.guest.network.device", null, "Specify the private bridge on host for private network", null),
// Premium
UsageExecutionTimezone("Premium", ManagementServer.class, String.class, "usage.execution.timezone", null, "The timezone to use for usage job execution time", null),
UsageStatsJobAggregationRange("Premium", ManagementServer.class, Integer.class, "usage.stats.job.aggregation.range", "1440", "The range of time for aggregating the user statistics specified in minutes (e.g. 1440 for daily, 60 for hourly.", null),
UsageStatsJobExecTime("Premium", ManagementServer.class, String.class, "usage.stats.job.exec.time", "00:15", "The time at which the usage statistics aggregation job will run as an HH24:MM time, e.g. 00:30 to run at 12:30am.", null),
EnableUsageServer("Premium", ManagementServer.class, Boolean.class, "enable.usage.server", "true", "Flag for enabling usage", null),
DirectNetworkStatsInterval("Premium", ManagementServer.class, Integer.class, "direct.network.stats.interval", "86400", "Interval (in seconds) to collect stats from Traffic Monitor", null),
// Hidden
UseSecondaryStorageVm("Hidden", ManagementServer.class, Boolean.class, "secondary.storage.vm", "false", "Deploys a VM per zone to manage secondary storage if true, otherwise secondary storage is mounted on management server", null),
CreatePoolsInPod("Hidden", ManagementServer.class, Boolean.class, "xen.create.pools.in.pod", "false", "Should we automatically add XenServers into pools that are inside a Pod", null),
CloudIdentifier("Hidden", ManagementServer.class, String.class, "cloud.identifier", null, "A unique identifier for the cloud.", null),
SSOKey("Hidden", ManagementServer.class, String.class, "security.singlesignon.key", null, "A Single Sign-On key used for logging into the cloud", null),
SSOAuthTolerance("Advanced", ManagementServer.class, Long.class, "security.singlesignon.tolerance.millis", "300000", "The allowable clock difference in milliseconds between when an SSO login request is made and when it is received.", null),
//NetworkType("Hidden", ManagementServer.class, String.class, "network.type", "vlan", "The type of network that this deployment will use.", "vlan,direct"),
HashKey("Hidden", ManagementServer.class, String.class, "security.hash.key", null, "for generic key-ed hash", null),
RouterRamSize("Hidden", NetworkManager.class, Integer.class, "router.ram.size", "128", "Default RAM for router VM (in MB).", null),
VmOpWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.op.wait.interval", "120", "Time (in seconds) to wait before checking if a previous operation has succeeded", null),
VmOpLockStateRetry("Advanced", ManagementServer.class, Integer.class, "vm.op.lock.state.retry", "5", "Times to retry locking the state of a VM for operations", "-1 means try forever"),
VmOpCleanupInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.interval", "86400", "Interval to run the thread that cleans up the vm operations (in seconds)", "Seconds"),
VmOpCleanupWait("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.wait", "3600", "Time (in seconds) to wait before cleanuping up any vm work items", "Seconds"),
VmOpCancelInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cancel.interval", "3600", "Time (in seconds) to wait before cancelling a operation", "Seconds"),
DefaultPageSize("Advanced", ManagementServer.class, Long.class, "default.page.size", "500", "Default page size for API list* commands", null),
TaskCleanupRetryInterval("Advanced", ManagementServer.class, Integer.class, "task.cleanup.retry.interval", "600", "Time (in seconds) to wait before retrying cleanup of tasks if the cleanup failed previously. 0 means to never retry.", "Seconds"),
// Account Default Limits
DefaultMaxAccountUserVms("Account Defaults", ManagementServer.class, Long.class, "max.account.user.vms", "20", "The default maximum number of user VMs that can be deployed for an account", null),
DefaultMaxAccountPublicIPs("Account Defaults", ManagementServer.class, Long.class, "max.account.public.ips", "20", "The default maximum number of public IPs that can be consumed by an account", null),
DefaultMaxAccountTemplates("Account Defaults", ManagementServer.class, Long.class, "max.account.templates", "20", "The default maximum number of templates that can be deployed for an account", null),
DefaultMaxAccountSnapshots("Account Defaults", ManagementServer.class, Long.class, "max.account.snapshots", "20", "The default maximum number of snapshots that can be created for an account", null),
DefaultMaxAccountVolumes("Account Defaults", ManagementServer.class, Long.class, "max.account.volumes", "20", "The default maximum number of volumes that can be created for an account", null),
DirectAgentLoadSize("Advanced", ManagementServer.class, Integer.class, "direct.agent.load.size", "16", "The number of direct agents to load each time", null);
private final String _category;
private final Class<?> _componentClass;
private final Class<?> _type;
private final String _name;
private final String _defaultValue;
private final String _description;
private final String _range;
private static final HashMap<String, List<Config>> _configs = new HashMap<String, List<Config>>();
static {
// Add categories
_configs.put("Alert", new ArrayList<Config>());
_configs.put("Storage", new ArrayList<Config>());
_configs.put("Snapshots", new ArrayList<Config>());
_configs.put("Network", new ArrayList<Config>());
_configs.put("Usage", new ArrayList<Config>());
_configs.put("Console Proxy", new ArrayList<Config>());
_configs.put("Advanced", new ArrayList<Config>());
_configs.put("Premium", new ArrayList<Config>());
_configs.put("Developer", new ArrayList<Config>());
_configs.put("Hidden", new ArrayList<Config>());
_configs.put("Account Defaults", new ArrayList<Config>());
// Add values into HashMap
for (Config c : Config.values()) {
String category = c.getCategory();
List<Config> currentConfigs = _configs.get(category);
currentConfigs.add(c);
_configs.put(category, currentConfigs);
}
}
private Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range) {
_category = category;
_componentClass = componentClass;
_type = type;
_name = name;
_defaultValue = defaultValue;
_description = description;
_range = range;
}
public String getCategory() {
return _category;
}
public String key() {
return _name;
}
public String getDescription() {
return _description;
}
public String getDefaultValue() {
return _defaultValue;
}
public Class<?> getType() {
return _type;
}
public Class<?> getComponentClass() {
return _componentClass;
}
public String getComponent() {
if (_componentClass == ManagementServer.class) {
return "management-server";
} else if (_componentClass == AgentManager.class) {
return "AgentManager";
} else if (_componentClass == UserVmManager.class) {
return "UserVmManager";
} else if (_componentClass == HighAvailabilityManager.class) {
return "HighAvailabilityManager";
} else if (_componentClass == StoragePoolAllocator.class) {
return "StorageAllocator";
} else {
return "none";
}
}
public String getRange() {
return _range;
}
@Override
public String toString() {
return _name;
}
public static List<Config> getConfigs(String category) {
return _configs.get(category);
}
public static Config getConfig(String name) {
List<String> categories = getCategories();
for (String category : categories) {
List<Config> currentList = getConfigs(category);
for (Config c : currentList) {
if (c.key().equals(name)) {
return c;
}
}
}
return null;
}
public static List<String> getCategories() {
Object[] keys = _configs.keySet().toArray();
List<String> categories = new ArrayList<String>();
for (Object key : keys) {
categories.add((String) key);
}
return categories;
}
}
| server/src/com/cloud/configuration/Config.java | /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.cloud.agent.AgentManager;
import com.cloud.consoleproxy.ConsoleProxyManager;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.NetworkManager;
import com.cloud.network.router.VirtualNetworkApplianceManager;
import com.cloud.server.ManagementServer;
import com.cloud.storage.StorageManager;
import com.cloud.storage.allocator.StoragePoolAllocator;
import com.cloud.storage.secondary.SecondaryStorageVmManager;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.vm.UserVmManager;
public enum Config {
// Alert
AlertEmailAddresses("Alert", ManagementServer.class, String.class, "alert.email.addresses", null, "Comma separated list of email addresses used for sending alerts.", null),
AlertEmailSender("Alert", ManagementServer.class, String.class, "alert.email.sender", null, "Sender of alert email (will be in the From header of the email).", null),
AlertSMTPHost("Alert", ManagementServer.class, String.class, "alert.smtp.host", null, "SMTP hostname used for sending out email alerts.", null),
AlertSMTPPassword("Alert", ManagementServer.class, String.class, "alert.smtp.password", null, "Password for SMTP authentication (applies only if alert.smtp.useAuth is true).", null),
AlertSMTPPort("Alert", ManagementServer.class, Integer.class, "alert.smtp.port", "465", "Port the SMTP server is listening on.", null),
AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null),
AlertSMTPUsername("Alert", ManagementServer.class, String.class, "alert.smtp.username", null, "Username for SMTP authentication (applies only if alert.smtp.useAuth is true).", null),
AlertWait("Alert", AgentManager.class, Integer.class, "alert.wait", null, "Seconds to wait before alerting on a disconnected agent", null),
// Storage
StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null),
StorageStatsInterval("Storage", ManagementServer.class, String.class, "storage.stats.interval", "60000", "The interval (in milliseconds) when storage stats (per host) are retrieved from agents.", null),
MaxVolumeSize("Storage", ManagementServer.class, Integer.class, "storage.max.volume.size", "2000", "The maximum size for a volume (in GB).", null),
TotalRetries("Storage", AgentManager.class, Integer.class, "total.retries", "4", "The number of times each command sent to a host should be retried in case of failure.", null),
// Network
GuestVlanBits("Network", ManagementServer.class, Integer.class, "guest.vlan.bits", "12", "The number of bits to reserve for the VLAN identifier in the guest subnet.", null),
//MulticastThrottlingRate("Network", ManagementServer.class, Integer.class, "multicast.throttling.rate", "10", "Default multicast rate in megabits per second allowed.", null),
NetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in network.", null),
GuestDomainSuffix("Network", AgentManager.class, String.class, "guest.domain.suffix", "cloud.internal", "Default domain name for vms inside virtualized networks fronted by router", null),
DirectNetworkNoDefaultRoute("Network", ManagementServer.class, Boolean.class, "direct.network.no.default.route", "false", "Direct Network Dhcp Server should not send a default route", "true/false"),
OvsNetwork("Network", ManagementServer.class, Boolean.class, "open.vswitch.vlan.network", "false", "enable/disable vlan remapping of open vswitch network", null),
OvsTunnelNetwork("Network", ManagementServer.class, Boolean.class, "open.vswitch.tunnel.network", "false", "enable/disable open vswitch tunnel network(no vlan)", null),
VmNetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "vm.network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in User vm's default network.", null),
//VPN
RemoteAccessVpnPskLength("Network", AgentManager.class, Integer.class, "remote.access.vpn.psk.length", "24", "The length of the ipsec preshared key (minimum 8, maximum 256)", null),
RemoteAccessVpnClientIpRange("Network", AgentManager.class, String.class, "remote.access.vpn.client.iprange", "10.1.2.1-10.1.2.8", "The range of ips to be allocated to remote access vpn clients. The first ip in the range is used by the VPN server", null),
RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null),
// Usage
CapacityCheckPeriod("Usage", ManagementServer.class, Integer.class, "capacity.check.period", "300000", "The interval in milliseconds between capacity checks", null),
StorageAllocatedCapacityThreshold("Usage", ManagementServer.class, Float.class, "storage.allocated.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of allocated storage utilization above which alerts will be sent about low storage available.", null),
StorageCapacityThreshold("Usage", ManagementServer.class, Float.class, "storage.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available.", null),
CPUCapacityThreshold("Usage", ManagementServer.class, Float.class, "cpu.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of cpu utilization above which alerts will be sent about low cpu available.", null),
MemoryCapacityThreshold("Usage", ManagementServer.class, Float.class, "memory.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of memory utilization above which alerts will be sent about low memory available.", null),
PublicIpCapacityThreshold("Usage", ManagementServer.class, Float.class, "public.ip.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of public IP address space utilization above which alerts will be sent.", null),
PrivateIpCapacityThreshold("Usage", ManagementServer.class, Float.class, "private.ip.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of private IP address space utilization above which alerts will be sent.", null),
// Console Proxy
ConsoleProxyCapacityStandby("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacity.standby", "10", "The minimal number of console proxy viewer sessions that system is able to serve immediately(standby capacity)", null),
ConsoleProxyCapacityScanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacityscan.interval", "30000", "The time interval(in millisecond) to scan whether or not system needs more console proxy to ensure minimal standby capacity", null),
ConsoleProxyCmdPort("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.cmd.port", "8001", "Console proxy command port that is used to communicate with management server", null),
ConsoleProxyRestart("Console Proxy", AgentManager.class, Boolean.class, "consoleproxy.restart", "true", "Console proxy restart flag, defaulted to true", null),
ConsoleProxyUrlDomain("Console Proxy", AgentManager.class, String.class, "consoleproxy.url.domain", "realhostip.com", "Console proxy url domain", null),
ConsoleProxyLoadscanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.loadscan.interval", "10000", "The time interval(in milliseconds) to scan console proxy working-load info", null),
ConsoleProxyRamSize("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.ram.size", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE), "RAM size (in MB) used to create new console proxy VMs", null),
ConsoleProxyCpuMHz("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.cpu.mhz", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_VM_CPUMHZ), "CPU speed (in MHz) used to create new console proxy VMs", null),
ConsoleProxySessionMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.max", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_CAPACITY), "The max number of viewer sessions console proxy is configured to serve for", null),
ConsoleProxySessionTimeout("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.timeout", "300000", "Timeout(in milliseconds) that console proxy tries to maintain a viewer session before it times out the session for no activity", null),
ConsoleProxyDisableRpFilter("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.disable.rpfilter", "true", "disable rp_filter on console proxy VM public interface", null),
ConsoleProxyLaunchMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.launch.max", "10", "maximum number of console proxy instances per zone can be launched", null),
ConsoleProxyManagementState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(),
"console proxy service management state", null),
ConsoleProxyManagementLastState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state.last", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(),
"last console proxy service management state", null),
// Snapshots
SnapshotHourlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.hourly", "8", "Maximum hourly snapshots for a volume", null),
SnapshotDailyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.daily", "8", "Maximum daily snapshots for a volume", null),
SnapshotWeeklyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.weekly", "8", "Maximum weekly snapshots for a volume", null),
SnapshotMonthlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.monthly", "8", "Maximum monthly snapshots for a volume", null),
SnapshotPollInterval("Snapshots", SnapshotManager.class, Integer.class, "snapshot.poll.interval", "300", "The time interval in seconds when the management server polls for snapshots to be scheduled.", null),
SnapshotDeltaMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.delta.max", "16", "max delta snapshots between two full snapshots.", null),
// Advanced
JobExpireMinutes("Advanced", ManagementServer.class, String.class, "job.expire.minutes", "1440", "Time (in minutes) for async-jobs to be kept in system", null),
JobCancelThresholdMinutes("Advanced", ManagementServer.class, String.class, "job.cancel.threshold.minutes", "60", "Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", null),
AccountCleanupInterval("Advanced", ManagementServer.class, Integer.class, "account.cleanup.interval", "86400", "The interval (in seconds) between cleanup for removed accounts", null),
AllowPublicUserTemplates("Advanced", ManagementServer.class, Integer.class, "allow.public.user.templates", "true", "If false, users will not be able to create public templates.", null),
InstanceName("Advanced", AgentManager.class, String.class, "instance.name", "VM", "Name of the deployment instance.", null),
ExpungeDelay("Advanced", UserVmManager.class, Integer.class, "expunge.delay", "86400", "Determines how long (in seconds) to wait before actually expunging destroyed vm. The default value = the default value of expunge.interval", null),
ExpungeInterval("Advanced", UserVmManager.class, Integer.class, "expunge.interval", "86400", "The interval (in seconds) to wait before running the expunge thread.", null),
ExpungeWorkers("Advanced", UserVmManager.class, Integer.class, "expunge.workers", "1", "Number of workers performing expunge ", null),
ExtractURLCleanUpInterval("Advanced", ManagementServer.class, Integer.class, "extract.url.cleanup.interval", "120", "The interval (in seconds) to wait before cleaning up the extract URL's ", null),
HostStatsInterval("Advanced", ManagementServer.class, Integer.class, "host.stats.interval", "60000", "The interval (in milliseconds) when host stats are retrieved from agents.", null),
HostRetry("Advanced", AgentManager.class, Integer.class, "host.retry", "2", "Number of times to retry hosts for creating a volume", null),
IntegrationAPIPort("Advanced", ManagementServer.class, Integer.class, "integration.api.port", "8096", "Defaul API port", null),
InvestigateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "investigate.retry.interval", "60", "Time (in seconds) between VM pings when agent is disconnected", null),
MigrateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "migrate.retry.interval", "120", "Time (in seconds) between migration retries", null),
PingInterval("Advanced", AgentManager.class, Integer.class, "ping.interval", "60", "Ping interval in seconds", null),
PingTimeout("Advanced", AgentManager.class, Float.class, "ping.timeout", "2.5", "Multiplier to ping.interval before announcing an agent has timed out", null),
Port("Advanced", AgentManager.class, Integer.class, "port", "8250", "Port to listen on for agent connection.", null),
RouterCpuMHz("Advanced", NetworkManager.class, Integer.class, "router.cpu.mhz", String.valueOf(VirtualNetworkApplianceManager.DEFAULT_ROUTER_CPU_MHZ), "Default CPU speed (MHz) for router VM.", null),
RestartRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "restart.retry.interval", "600", "Time (in seconds) between retries to restart a vm", null),
RouterStatsInterval("Advanced", NetworkManager.class, Integer.class, "router.stats.interval", "300", "Interval (in seconds) to report router statistics.", null),
RouterTemplateId("Advanced", NetworkManager.class, Long.class, "router.template.id", "1", "Default ID for template.", null),
StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null),
StopRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "stop.retry.interval", "600", "Time in seconds between retries to stop or destroy a vm" , null),
StorageCleanupInterval("Advanced", StorageManager.class, Integer.class, "storage.cleanup.interval", "86400", "The interval (in seconds) to wait before running the storage cleanup thread.", null),
StorageCleanupEnabled("Advanced", StorageManager.class, Boolean.class, "storage.cleanup.enabled", "true", "Enables/disables the storage cleanup thread.", null),
UpdateWait("Advanced", AgentManager.class, Integer.class, "update.wait", "600", "Time to wait (in seconds) before alerting on a updating agent", null),
Wait("Advanced", AgentManager.class, Integer.class, "wait", "1800", "Time in seconds to wait for control commands to return", null),
XapiWait("Advanced", AgentManager.class, Integer.class, "xapiwait", "600", "Time (in seconds) to wait for XAPI to return", null),
CmdsWait("Advanced", AgentManager.class, Integer.class, "cmd.wait", "7200", "Time (in seconds) to wait for some heavy time-consuming commands", null),
Workers("Advanced", AgentManager.class, Integer.class, "workers", "5", "Number of worker threads.", null),
MountParent("Advanced", ManagementServer.class, String.class, "mount.parent", "/var/lib/cloud/mnt", "The mount point on the Management Server for Secondary Storage.", null),
// UpgradeURL("Advanced", ManagementServer.class, String.class, "upgrade.url", "http://example.com:8080/client/agent/update.zip", "The upgrade URL is the URL of the management server that agents will connect to in order to automatically upgrade.", null),
SystemVMUseLocalStorage("Advanced", ManagementServer.class, Boolean.class, "system.vm.use.local.storage", "false", "Indicates whether to use local storage pools or shared storage pools for system VMs.", null),
SystemVMAutoReserveCapacity("Advanced", ManagementServer.class, Boolean.class, "system.vm.auto.reserve.capacity", "true", "Indicates whether or not to automatically reserver system VM standby capacity.", null),
CPUOverprovisioningFactor("Advanced", ManagementServer.class, String.class, "cpu.overprovisioning.factor", "1", "Used for CPU overprovisioning calculation; available CPU will be (actualCpuCapacity * cpu.overprovisioning.factor)", null),
LinkLocalIpNums("Advanced", ManagementServer.class, Integer.class, "linkLocalIp.nums", "10", "The number of link local ip that needed by domR(in power of 2)", null),
HypervisorList("Advanced", ManagementServer.class, String.class, "hypervisor.list", HypervisorType.KVM + "," + HypervisorType.XenServer + "," + HypervisorType.VMware + "," + HypervisorType.BareMetal, "The list of hypervisors that this deployment will use.", "hypervisorList"),
ManagementHostIPAdr("Advanced", ManagementServer.class, String.class, "host", "localhost", "The ip address of management server", null),
ManagementNetwork("Advanced", ManagementServer.class, String.class, "management.network.cidr", null, "The cidr of management server network", null),
EventPurgeDelay("Advanced", ManagementServer.class, Integer.class, "event.purge.delay", "15", "Events older than specified number days will be purged. Set this value to 0 to never delete events", null),
UseLocalStorage("Premium", ManagementServer.class, Boolean.class, "use.local.storage", "false", "Should we use the local storage if it's available?", null),
SecStorageVmRamSize("Advanced", AgentManager.class, Integer.class, "secstorage.vm.ram.size", String.valueOf(SecondaryStorageVmManager.DEFAULT_SS_VM_RAMSIZE), "RAM size (in MB) used to create new secondary storage vms", null),
SecStorageVmCpuMHz("Advanced", AgentManager.class, Integer.class, "secstorage.vm.cpu.mhz", String.valueOf(SecondaryStorageVmManager.DEFAULT_SS_VM_CPUMHZ), "CPU speed (in MHz) used to create new secondary storage vms", null),
MaxTemplateAndIsoSize("Advanced", ManagementServer.class, Long.class, "max.template.iso.size", "50", "The maximum size for a downloaded template or ISO (in GB).", null),
SecStorageAllowedInternalDownloadSites("Advanced", ManagementServer.class, String.class, "secstorage.allowed.internal.sites", null, "Comma separated list of cidrs internal to the datacenter that can host template download servers", null),
SecStorageEncryptCopy("Advanced", ManagementServer.class, Boolean.class, "secstorage.encrypt.copy", "false", "Use SSL method used to encrypt copy traffic between zones", "true,false"),
SecStorageSecureCopyCert("Advanced", ManagementServer.class, String.class, "secstorage.ssl.cert.domain", "realhostip.com", "SSL certificate used to encrypt copy traffic between zones", null),
SecStorageCapacityStandby("Advanced", AgentManager.class, Integer.class, "secstorage.capacity.standby", "10", "The minimal number of command execution sessions that system is able to serve immediately(standby capacity)", null),
SecStorageSessionMax("Advanced", AgentManager.class, Integer.class, "secstorage.session.max", "50", "The max number of command execution sessions that a SSVM can handle", null),
SecStorageCmdExecutionTimeMax("Advanced", AgentManager.class, Integer.class, "secstorage.cmd.execution.time.max", "30", "The max command execution time in minute", null),
DirectAttachNetworkEnabled("Advanced", ManagementServer.class, Boolean.class, "direct.attach.network.externalIpAllocator.enabled", "false", "Direct-attach VMs using external DHCP server", "true,false"),
DirectAttachNetworkExternalAPIURL("Advanced", ManagementServer.class, String.class, "direct.attach.network.externalIpAllocator.url", null, "Direct-attach VMs using external DHCP server (API url)", null),
CheckPodCIDRs("Advanced", ManagementServer.class, String.class, "check.pod.cidrs", "true", "If true, different pods must belong to different CIDR subnets.", "true,false"),
NetworkGcWait("Advanced", ManagementServer.class, Integer.class, "network.gc.wait", "600", "Time (in seconds) to wait before shutting down a network that's not in used", null),
NetworkGcInterval("Advanced", ManagementServer.class, Integer.class, "network.gc.interval", "600", "Seconds to wait before checking for networks to shutdown", null),
HostCapacityCheckerWait("Advanced", ManagementServer.class, Integer.class, "host.capacity.checker.wait", "3600", "Time (in seconds) to wait before starting host capacity background checker", null),
HostCapacityCheckerInterval("Advanced", ManagementServer.class, Integer.class, "host.capacity.checker.interval", "3600", "Time (in seconds) to wait before recalculating host's capacity", null),
CapacitySkipcountingHours("Advanced", ManagementServer.class, Integer.class, "capacity.skipcounting.hours", "3600", "Time (in seconds) to wait before release VM's cpu and memory when VM in stopped state", null),
VmStatsInterval("Advanced", ManagementServer.class, Integer.class, "vm.stats.interval", "60000", "The interval (in milliseconds) when vm stats are retrieved from agents.", null),
VmTransitionWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.tranisition.wait.interval", "3600", "Time (in seconds) to wait before taking over a VM in transition state", null),
ControlCidr("Advanced", ManagementServer.class, String.class, "control.cidr", "169.254.0.0/16", "Changes the cidr for the control network traffic. Defaults to using link local. Must be unique within pods", null),
ControlGateway("Advanced", ManagementServer.class, String.class, "control.gateway", "169.254.0.1", "gateway for the control network traffic", null),
UseUserConcentratedPodAllocation("Advanced", ManagementServer.class, Boolean.class, "use.user.concentrated.pod.allocation", "true", "If true, deployment planner applies the user concentration heuristic during VM resource allocation", "true,false"),
HostCapacityTypeToOrderClusters("Advanced", ManagementServer.class, String.class, "host.capacityType.to.order.clusters", "CPU", "The host capacity type (CPU or RAM) is used by deployment planner to order clusters during VM resource allocation", "CPU,RAM"),
EndpointeUrl("Advanced", ManagementServer.class, String.class, "endpointe.url", "http://localhost:8080/client/api", "Endpointe Url", "The endpoint callback URL"),
// XenServer
VmAllocationAlgorithm("Advanced", ManagementServer.class, String.class, "vm.allocation.algorithm", "random", "If 'random', hosts within a pod will be randomly considered for VM/volume allocation. If 'firstfit', they will be considered on a first-fit basis.", null),
XenPublicNetwork("Network", ManagementServer.class, String.class, "xen.public.network.device", null, "[ONLY IF THE PUBLIC NETWORK IS ON A DEDICATED NIC]:The network name label of the physical device dedicated to the public network on a XenServer host", null),
XenStorageNetwork1("Network", ManagementServer.class, String.class, "xen.storage.network.device1", "cloud-stor1", "Specify when there are storage networks", null),
XenStorageNetwork2("Network", ManagementServer.class, String.class, "xen.storage.network.device2", "cloud-stor2", "Specify when there are storage networks", null),
XenPrivateNetwork("Network", ManagementServer.class, String.class, "xen.private.network.device", null, "Specify when the private network name is different", null),
NetworkGuestCidrLimit("Network", NetworkManager.class, Integer.class, "network.guest.cidr.limit", "22", "size limit for guest cidr; can't be less than this value", null),
XenMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.version", "3.3.1", "Minimum Xen version", null),
XenProductMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.product.version", "0.1.1", "Minimum XenServer version", null),
XenXapiMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.xapi.version", "1.3", "Minimum Xapi Tool Stack version", null),
XenMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.version", "3.4.2", "Maximum Xen version", null),
XenProductMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.product.version", "5.6.0", "Maximum XenServer version", null),
XenXapiMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.xapi.version", "1.3", "Maximum Xapi Tool Stack version", null),
XenSetupMultipath("Advanced", ManagementServer.class, String.class, "xen.setup.multipath", "false", "Setup the host to do multipath", null),
XenBondStorageNic("Advanced", ManagementServer.class, String.class, "xen.bond.storage.nics", null, "Attempt to bond the two networks if found", null),
XenHeartBeatInterval("Advanced", ManagementServer.class, Integer.class, "xen.heartbeat.interval", "60", "heartbeat to use when implementing XenServer Self Fencing", null),
XenGuestNetwork("Advanced", ManagementServer.class, String.class, "xen.guest.network.device", null, "Specify for guest network name label", null),
// VMware
VmwarePrivateNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.private.vswitch", null, "Specify the vSwitch on host for private network", null),
VmwarePublicNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.public.vswitch", null, "Specify the vSwitch on host for public network", null),
VmwareGuestNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.guest.vswitch", null, "Specify the vSwitch on host for guest network", null),
VmwareServiceConsole("Advanced", ManagementServer.class, String.class, "vmware.service.console", "Service Console", "Specify the service console network name (ESX host only)", null),
// KVM
KvmPublicNetwork("Advanced", ManagementServer.class, String.class, "kvm.public.network.device", null, "Specify the public bridge on host for public network", null),
KvmPrivateNetwork("Advanced", ManagementServer.class, String.class, "kvm.private.network.device", null, "Specify the private bridge on host for private network", null),
KvmGuestNetwork("Advanced", ManagementServer.class, String.class, "kvm.guest.network.device", null, "Specify the private bridge on host for private network", null),
// Premium
UsageExecutionTimezone("Premium", ManagementServer.class, String.class, "usage.execution.timezone", null, "The timezone to use for usage job execution time", null),
UsageStatsJobAggregationRange("Premium", ManagementServer.class, Integer.class, "usage.stats.job.aggregation.range", "1440", "The range of time for aggregating the user statistics specified in minutes (e.g. 1440 for daily, 60 for hourly.", null),
UsageStatsJobExecTime("Premium", ManagementServer.class, String.class, "usage.stats.job.exec.time", "00:15", "The time at which the usage statistics aggregation job will run as an HH24:MM time, e.g. 00:30 to run at 12:30am.", null),
EnableUsageServer("Premium", ManagementServer.class, Boolean.class, "enable.usage.server", "true", "Flag for enabling usage", null),
DirectNetworkStatsInterval("Premium", ManagementServer.class, Integer.class, "direct.network.stats.interval", "84600", "Interval (in seconds) to collect stats from Traffic Monitor", null),
// Hidden
UseSecondaryStorageVm("Hidden", ManagementServer.class, Boolean.class, "secondary.storage.vm", "false", "Deploys a VM per zone to manage secondary storage if true, otherwise secondary storage is mounted on management server", null),
CreatePoolsInPod("Hidden", ManagementServer.class, Boolean.class, "xen.create.pools.in.pod", "false", "Should we automatically add XenServers into pools that are inside a Pod", null),
CloudIdentifier("Hidden", ManagementServer.class, String.class, "cloud.identifier", null, "A unique identifier for the cloud.", null),
SSOKey("Hidden", ManagementServer.class, String.class, "security.singlesignon.key", null, "A Single Sign-On key used for logging into the cloud", null),
SSOAuthTolerance("Advanced", ManagementServer.class, Long.class, "security.singlesignon.tolerance.millis", "300000", "The allowable clock difference in milliseconds between when an SSO login request is made and when it is received.", null),
//NetworkType("Hidden", ManagementServer.class, String.class, "network.type", "vlan", "The type of network that this deployment will use.", "vlan,direct"),
HashKey("Hidden", ManagementServer.class, String.class, "security.hash.key", null, "for generic key-ed hash", null),
RouterRamSize("Hidden", NetworkManager.class, Integer.class, "router.ram.size", "128", "Default RAM for router VM (in MB).", null),
VmOpWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.op.wait.interval", "120", "Time (in seconds) to wait before checking if a previous operation has succeeded", null),
VmOpLockStateRetry("Advanced", ManagementServer.class, Integer.class, "vm.op.lock.state.retry", "5", "Times to retry locking the state of a VM for operations", "-1 means try forever"),
VmOpCleanupInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.interval", "86400", "Interval to run the thread that cleans up the vm operations (in seconds)", "Seconds"),
VmOpCleanupWait("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.wait", "3600", "Time (in seconds) to wait before cleanuping up any vm work items", "Seconds"),
VmOpCancelInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cancel.interval", "3600", "Time (in seconds) to wait before cancelling a operation", "Seconds"),
DefaultPageSize("Advanced", ManagementServer.class, Long.class, "default.page.size", "500", "Default page size for API list* commands", null),
TaskCleanupRetryInterval("Advanced", ManagementServer.class, Integer.class, "task.cleanup.retry.interval", "600", "Time (in seconds) to wait before retrying cleanup of tasks if the cleanup failed previously. 0 means to never retry.", "Seconds"),
// Account Default Limits
DefaultMaxAccountUserVms("Account Defaults", ManagementServer.class, Long.class, "max.account.user.vms", "20", "The default maximum number of user VMs that can be deployed for an account", null),
DefaultMaxAccountPublicIPs("Account Defaults", ManagementServer.class, Long.class, "max.account.public.ips", "20", "The default maximum number of public IPs that can be consumed by an account", null),
DefaultMaxAccountTemplates("Account Defaults", ManagementServer.class, Long.class, "max.account.templates", "20", "The default maximum number of templates that can be deployed for an account", null),
DefaultMaxAccountSnapshots("Account Defaults", ManagementServer.class, Long.class, "max.account.snapshots", "20", "The default maximum number of snapshots that can be created for an account", null),
DefaultMaxAccountVolumes("Account Defaults", ManagementServer.class, Long.class, "max.account.volumes", "20", "The default maximum number of volumes that can be created for an account", null),
DirectAgentLoadSize("Advanced", ManagementServer.class, Integer.class, "direct.agent.load.size", "16", "The number of direct agents to load each time", null);
private final String _category;
private final Class<?> _componentClass;
private final Class<?> _type;
private final String _name;
private final String _defaultValue;
private final String _description;
private final String _range;
private static final HashMap<String, List<Config>> _configs = new HashMap<String, List<Config>>();
static {
// Add categories
_configs.put("Alert", new ArrayList<Config>());
_configs.put("Storage", new ArrayList<Config>());
_configs.put("Snapshots", new ArrayList<Config>());
_configs.put("Network", new ArrayList<Config>());
_configs.put("Usage", new ArrayList<Config>());
_configs.put("Console Proxy", new ArrayList<Config>());
_configs.put("Advanced", new ArrayList<Config>());
_configs.put("Premium", new ArrayList<Config>());
_configs.put("Developer", new ArrayList<Config>());
_configs.put("Hidden", new ArrayList<Config>());
_configs.put("Account Defaults", new ArrayList<Config>());
// Add values into HashMap
for (Config c : Config.values()) {
String category = c.getCategory();
List<Config> currentConfigs = _configs.get(category);
currentConfigs.add(c);
_configs.put(category, currentConfigs);
}
}
private Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range) {
_category = category;
_componentClass = componentClass;
_type = type;
_name = name;
_defaultValue = defaultValue;
_description = description;
_range = range;
}
public String getCategory() {
return _category;
}
public String key() {
return _name;
}
public String getDescription() {
return _description;
}
public String getDefaultValue() {
return _defaultValue;
}
public Class<?> getType() {
return _type;
}
public Class<?> getComponentClass() {
return _componentClass;
}
public String getComponent() {
if (_componentClass == ManagementServer.class) {
return "management-server";
} else if (_componentClass == AgentManager.class) {
return "AgentManager";
} else if (_componentClass == UserVmManager.class) {
return "UserVmManager";
} else if (_componentClass == HighAvailabilityManager.class) {
return "HighAvailabilityManager";
} else if (_componentClass == StoragePoolAllocator.class) {
return "StorageAllocator";
} else {
return "none";
}
}
public String getRange() {
return _range;
}
@Override
public String toString() {
return _name;
}
public static List<Config> getConfigs(String category) {
return _configs.get(category);
}
public static Config getConfig(String name) {
List<String> categories = getCategories();
for (String category : categories) {
List<Config> currentList = getConfigs(category);
for (Config c : currentList) {
if (c.key().equals(name)) {
return c;
}
}
}
return null;
}
public static List<String> getCategories() {
Object[] keys = _configs.keySet().toArray();
List<String> categories = new ArrayList<String>();
for (Object key : keys) {
categories.add((String) key);
}
return categories;
}
}
| bug 8866: Use 86400 instead of 84600 for seconds in a day
| server/src/com/cloud/configuration/Config.java | bug 8866: Use 86400 instead of 84600 for seconds in a day | <ide><path>erver/src/com/cloud/configuration/Config.java
<ide> UsageStatsJobAggregationRange("Premium", ManagementServer.class, Integer.class, "usage.stats.job.aggregation.range", "1440", "The range of time for aggregating the user statistics specified in minutes (e.g. 1440 for daily, 60 for hourly.", null),
<ide> UsageStatsJobExecTime("Premium", ManagementServer.class, String.class, "usage.stats.job.exec.time", "00:15", "The time at which the usage statistics aggregation job will run as an HH24:MM time, e.g. 00:30 to run at 12:30am.", null),
<ide> EnableUsageServer("Premium", ManagementServer.class, Boolean.class, "enable.usage.server", "true", "Flag for enabling usage", null),
<del> DirectNetworkStatsInterval("Premium", ManagementServer.class, Integer.class, "direct.network.stats.interval", "84600", "Interval (in seconds) to collect stats from Traffic Monitor", null),
<add> DirectNetworkStatsInterval("Premium", ManagementServer.class, Integer.class, "direct.network.stats.interval", "86400", "Interval (in seconds) to collect stats from Traffic Monitor", null),
<ide>
<ide> // Hidden
<ide> UseSecondaryStorageVm("Hidden", ManagementServer.class, Boolean.class, "secondary.storage.vm", "false", "Deploys a VM per zone to manage secondary storage if true, otherwise secondary storage is mounted on management server", null), |
|
JavaScript | mit | afefaa840a4881a2d91c528620c5be55645acfb5 | 0 | knowledge-map/knowledge-map.github.io,knowledge-map/cartographer | "use strict";
var knowledge = {
concepts: [
{
id: "edit",
name: "Click here to edit!"
},
{
id: "dependency",
name: "Click the top of the concept to add a dependency concept",
dependencies: ["edit"]
},
{
id: "dependent",
name: "Click the bottom of the concept to add a dependent concept",
dependencies: ["edit"]
},
{
id: "joining",
name: "Drag from one concept to another to add dependencies",
dependencies: ["edit"]
},
{
id: "removing",
name: "Drag between a concept and its dependency to remove the connection",
dependencies: ["joining"]
}
]
};
// Create graph that visualises the knowledge
knowledgeGraph.create({
graph: knowledge,
plugins: [knowledgeGraph.plugins.editing],
});
| demo/edit.js | "use strict";
var knowledge = {
concepts: [
{
id: "edit",
name: "Click here to edit!"
},
{
id: "dependency",
name: "Click the top of the concept to add a dependency concept",
dependencies: ["edit"]
},
{
id: "dependent",
name: "Click the bottom of the concept to add a dependent concept",
dependencies: ["edit"]
},
{
id: "joining",
name: "Drag from one node to another to add dependencies",
dependencies: ["edit"]
}
]
};
// Create graph that visualises the knowledge
knowledgeGraph.create({
graph: knowledge,
plugins: [knowledgeGraph.plugins.editing],
});
| Added dependency deletion to editing demo
Dependency deletion doesn't actually exist yet though
| demo/edit.js | Added dependency deletion to editing demo | <ide><path>emo/edit.js
<ide> },
<ide> {
<ide> id: "joining",
<del> name: "Drag from one node to another to add dependencies",
<add> name: "Drag from one concept to another to add dependencies",
<ide> dependencies: ["edit"]
<add> },
<add> {
<add> id: "removing",
<add> name: "Drag between a concept and its dependency to remove the connection",
<add> dependencies: ["joining"]
<ide> }
<ide> ]
<ide> }; |
|
Java | apache-2.0 | 673531284fafaa53cee1ae26a0cd407e74f4e07a | 0 | nooone/libgdx,haedri/libgdx-1,sjosegarcia/libgdx,kzganesan/libgdx,Arcnor/libgdx,nelsonsilva/libgdx,Senth/libgdx,PedroRomanoBarbosa/libgdx,fwolff/libgdx,petugez/libgdx,jsjolund/libgdx,tell10glu/libgdx,nave966/libgdx,nave966/libgdx,lordjone/libgdx,tommycli/libgdx,EsikAntony/libgdx,saltares/libgdx,tell10glu/libgdx,haedri/libgdx-1,hyvas/libgdx,fwolff/libgdx,kzganesan/libgdx,js78/libgdx,Thotep/libgdx,Arcnor/libgdx,tommycli/libgdx,gouessej/libgdx,josephknight/libgdx,anserran/libgdx,xoppa/libgdx,Wisienkas/libgdx,curtiszimmerman/libgdx,junkdog/libgdx,FyiurAmron/libgdx,junkdog/libgdx,cypherdare/libgdx,andyvand/libgdx,ricardorigodon/libgdx,thepullman/libgdx,bgroenks96/libgdx,ryoenji/libgdx,collinsmith/libgdx,zommuter/libgdx,Senth/libgdx,copystudy/libgdx,srwonka/libGdx,czyzby/libgdx,gf11speed/libgdx,kotcrab/libgdx,MikkelTAndersen/libgdx,alireza-hosseini/libgdx,JFixby/libgdx,nrallakis/libgdx,copystudy/libgdx,fiesensee/libgdx,Arcnor/libgdx,noelsison2/libgdx,samskivert/libgdx,snovak/libgdx,FyiurAmron/libgdx,NathanSweet/libgdx,jasonwee/libgdx,Deftwun/libgdx,snovak/libgdx,EsikAntony/libgdx,Senth/libgdx,tell10glu/libgdx,Zonglin-Li6565/libgdx,jsjolund/libgdx,andyvand/libgdx,collinsmith/libgdx,firefly2442/libgdx,Wisienkas/libgdx,billgame/libgdx,nrallakis/libgdx,lordjone/libgdx,basherone/libgdxcn,bladecoder/libgdx,kagehak/libgdx,firefly2442/libgdx,Gliby/libgdx,czyzby/libgdx,MetSystem/libgdx,Heart2009/libgdx,toa5/libgdx,realitix/libgdx,zommuter/libgdx,titovmaxim/libgdx,MetSystem/libgdx,mumer92/libgdx,JDReutt/libgdx,czyzby/libgdx,Xhanim/libgdx,jsjolund/libgdx,nudelchef/libgdx,saltares/libgdx,andyvand/libgdx,djom20/libgdx,toloudis/libgdx,JFixby/libgdx,azakhary/libgdx,Deftwun/libgdx,kagehak/libgdx,PedroRomanoBarbosa/libgdx,shiweihappy/libgdx,nelsonsilva/libgdx,gouessej/libgdx,gdos/libgdx,junkdog/libgdx,BlueRiverInteractive/libgdx,MathieuDuponchelle/gdx,saltares/libgdx,ninoalma/libgdx,alex-dorokhov/libgdx,Deftwun/libgdx,ttencate/libgdx,nudelchef/libgdx,srwonka/libGdx,fiesensee/libgdx,hyvas/libgdx,gdos/libgdx,Gliby/libgdx,yangweigbh/libgdx,sinistersnare/libgdx,SidneyXu/libgdx,youprofit/libgdx,cypherdare/libgdx,Heart2009/libgdx,cypherdare/libgdx,bladecoder/libgdx,snovak/libgdx,Gliby/libgdx,MetSystem/libgdx,Wisienkas/libgdx,designcrumble/libgdx,KrisLee/libgdx,samskivert/libgdx,noelsison2/libgdx,ryoenji/libgdx,xpenatan/libgdx-LWJGL3,FredGithub/libgdx,saltares/libgdx,lordjone/libgdx,stinsonga/libgdx,titovmaxim/libgdx,sinistersnare/libgdx,copystudy/libgdx,nelsonsilva/libgdx,Zomby2D/libgdx,Xhanim/libgdx,fwolff/libgdx,noelsison2/libgdx,petugez/libgdx,antag99/libgdx,MetSystem/libgdx,Zomby2D/libgdx,yangweigbh/libgdx,libgdx/libgdx,gdos/libgdx,GreenLightning/libgdx,tommyettinger/libgdx,309746069/libgdx,lordjone/libgdx,1yvT0s/libgdx,GreenLightning/libgdx,MovingBlocks/libgdx,saqsun/libgdx,designcrumble/libgdx,del-sol/libgdx,xranby/libgdx,Heart2009/libgdx,Thotep/libgdx,gf11speed/libgdx,samskivert/libgdx,fiesensee/libgdx,youprofit/libgdx,realitix/libgdx,EsikAntony/libgdx,Thotep/libgdx,FredGithub/libgdx,junkdog/libgdx,kagehak/libgdx,nudelchef/libgdx,tell10glu/libgdx,luischavez/libgdx,JFixby/libgdx,sinistersnare/libgdx,SidneyXu/libgdx,libgdx/libgdx,samskivert/libgdx,djom20/libgdx,Zonglin-Li6565/libgdx,srwonka/libGdx,titovmaxim/libgdx,samskivert/libgdx,copystudy/libgdx,Gliby/libgdx,jberberick/libgdx,nooone/libgdx,TheAks999/libgdx,SidneyXu/libgdx,xoppa/libgdx,firefly2442/libgdx,zommuter/libgdx,hyvas/libgdx,bgroenks96/libgdx,sjosegarcia/libgdx,MadcowD/libgdx,UnluckyNinja/libgdx,bsmr-java/libgdx,designcrumble/libgdx,Heart2009/libgdx,KrisLee/libgdx,JDReutt/libgdx,alex-dorokhov/libgdx,realitix/libgdx,bsmr-java/libgdx,jberberick/libgdx,collinsmith/libgdx,GreenLightning/libgdx,BlueRiverInteractive/libgdx,ztv/libgdx,NathanSweet/libgdx,Xhanim/libgdx,yangweigbh/libgdx,Wisienkas/libgdx,JDReutt/libgdx,ya7lelkom/libgdx,shiweihappy/libgdx,zhimaijoy/libgdx,jsjolund/libgdx,nrallakis/libgdx,czyzby/libgdx,alireza-hosseini/libgdx,xoppa/libgdx,bgroenks96/libgdx,andyvand/libgdx,Arcnor/libgdx,BlueRiverInteractive/libgdx,gouessej/libgdx,designcrumble/libgdx,noelsison2/libgdx,basherone/libgdxcn,KrisLee/libgdx,katiepino/libgdx,bsmr-java/libgdx,stinsonga/libgdx,luischavez/libgdx,Zonglin-Li6565/libgdx,JFixby/libgdx,bgroenks96/libgdx,billgame/libgdx,Senth/libgdx,antag99/libgdx,MovingBlocks/libgdx,KrisLee/libgdx,TheAks999/libgdx,basherone/libgdxcn,Heart2009/libgdx,luischavez/libgdx,andyvand/libgdx,thepullman/libgdx,davebaol/libgdx,saqsun/libgdx,nudelchef/libgdx,yangweigbh/libgdx,billgame/libgdx,nooone/libgdx,luischavez/libgdx,noelsison2/libgdx,ninoalma/libgdx,NathanSweet/libgdx,codepoke/libgdx,PedroRomanoBarbosa/libgdx,xpenatan/libgdx-LWJGL3,toa5/libgdx,PedroRomanoBarbosa/libgdx,curtiszimmerman/libgdx,billgame/libgdx,snovak/libgdx,josephknight/libgdx,copystudy/libgdx,anserran/libgdx,jasonwee/libgdx,Badazdz/libgdx,collinsmith/libgdx,flaiker/libgdx,MadcowD/libgdx,samskivert/libgdx,srwonka/libGdx,ztv/libgdx,Wisienkas/libgdx,flaiker/libgdx,gf11speed/libgdx,FredGithub/libgdx,saqsun/libgdx,srwonka/libGdx,ttencate/libgdx,MadcowD/libgdx,gf11speed/libgdx,mumer92/libgdx,stinsonga/libgdx,ttencate/libgdx,309746069/libgdx,youprofit/libgdx,kotcrab/libgdx,kotcrab/libgdx,lordjone/libgdx,basherone/libgdxcn,jasonwee/libgdx,fwolff/libgdx,jsjolund/libgdx,stickyd/libgdx,stickyd/libgdx,ryoenji/libgdx,ya7lelkom/libgdx,petugez/libgdx,kotcrab/libgdx,FyiurAmron/libgdx,PedroRomanoBarbosa/libgdx,Heart2009/libgdx,youprofit/libgdx,bladecoder/libgdx,curtiszimmerman/libgdx,sarkanyi/libgdx,MovingBlocks/libgdx,xranby/libgdx,josephknight/libgdx,josephknight/libgdx,libgdx/libgdx,gf11speed/libgdx,codepoke/libgdx,309746069/libgdx,codepoke/libgdx,sinistersnare/libgdx,billgame/libgdx,thepullman/libgdx,ninoalma/libgdx,antag99/libgdx,fiesensee/libgdx,hyvas/libgdx,ztv/libgdx,samskivert/libgdx,Wisienkas/libgdx,1yvT0s/libgdx,stickyd/libgdx,stinsonga/libgdx,sarkanyi/libgdx,del-sol/libgdx,Heart2009/libgdx,collinsmith/libgdx,MathieuDuponchelle/gdx,ztv/libgdx,gdos/libgdx,ya7lelkom/libgdx,nelsonsilva/libgdx,gouessej/libgdx,curtiszimmerman/libgdx,bladecoder/libgdx,ttencate/libgdx,zommuter/libgdx,revo09/libgdx,FyiurAmron/libgdx,djom20/libgdx,firefly2442/libgdx,JFixby/libgdx,collinsmith/libgdx,BlueRiverInteractive/libgdx,Badazdz/libgdx,copystudy/libgdx,realitix/libgdx,nudelchef/libgdx,katiepino/libgdx,basherone/libgdxcn,fwolff/libgdx,toloudis/libgdx,fwolff/libgdx,luischavez/libgdx,realitix/libgdx,MadcowD/libgdx,alex-dorokhov/libgdx,Badazdz/libgdx,kagehak/libgdx,MathieuDuponchelle/gdx,hyvas/libgdx,alex-dorokhov/libgdx,alireza-hosseini/libgdx,youprofit/libgdx,libgdx/libgdx,bsmr-java/libgdx,ninoalma/libgdx,andyvand/libgdx,anserran/libgdx,MovingBlocks/libgdx,UnluckyNinja/libgdx,revo09/libgdx,kzganesan/libgdx,FredGithub/libgdx,jberberick/libgdx,FredGithub/libgdx,del-sol/libgdx,djom20/libgdx,ztv/libgdx,ztv/libgdx,sjosegarcia/libgdx,xoppa/libgdx,ThiagoGarciaAlves/libgdx,Badazdz/libgdx,sjosegarcia/libgdx,SidneyXu/libgdx,nave966/libgdx,MikkelTAndersen/libgdx,toloudis/libgdx,zhimaijoy/libgdx,mumer92/libgdx,saqsun/libgdx,ya7lelkom/libgdx,Xhanim/libgdx,xpenatan/libgdx-LWJGL3,petugez/libgdx,SidneyXu/libgdx,fwolff/libgdx,jberberick/libgdx,sjosegarcia/libgdx,ricardorigodon/libgdx,FredGithub/libgdx,thepullman/libgdx,josephknight/libgdx,jsjolund/libgdx,EsikAntony/libgdx,del-sol/libgdx,petugez/libgdx,designcrumble/libgdx,PedroRomanoBarbosa/libgdx,KrisLee/libgdx,thepullman/libgdx,ThiagoGarciaAlves/libgdx,davebaol/libgdx,nrallakis/libgdx,haedri/libgdx-1,kzganesan/libgdx,1yvT0s/libgdx,nrallakis/libgdx,Badazdz/libgdx,Dzamir/libgdx,xpenatan/libgdx-LWJGL3,Zonglin-Li6565/libgdx,designcrumble/libgdx,stickyd/libgdx,JFixby/libgdx,flaiker/libgdx,davebaol/libgdx,toa5/libgdx,djom20/libgdx,309746069/libgdx,antag99/libgdx,JFixby/libgdx,sinistersnare/libgdx,nooone/libgdx,ninoalma/libgdx,JDReutt/libgdx,MadcowD/libgdx,Dzamir/libgdx,kagehak/libgdx,haedri/libgdx-1,Dzamir/libgdx,saqsun/libgdx,SidneyXu/libgdx,gdos/libgdx,antag99/libgdx,curtiszimmerman/libgdx,Zonglin-Li6565/libgdx,titovmaxim/libgdx,davebaol/libgdx,MetSystem/libgdx,MikkelTAndersen/libgdx,snovak/libgdx,Deftwun/libgdx,czyzby/libgdx,thepullman/libgdx,firefly2442/libgdx,xoppa/libgdx,ThiagoGarciaAlves/libgdx,JDReutt/libgdx,bgroenks96/libgdx,JDReutt/libgdx,haedri/libgdx-1,BlueRiverInteractive/libgdx,ricardorigodon/libgdx,UnluckyNinja/libgdx,billgame/libgdx,shiweihappy/libgdx,toa5/libgdx,BlueRiverInteractive/libgdx,mumer92/libgdx,youprofit/libgdx,antag99/libgdx,jasonwee/libgdx,fwolff/libgdx,UnluckyNinja/libgdx,zhimaijoy/libgdx,gf11speed/libgdx,tell10glu/libgdx,azakhary/libgdx,zommuter/libgdx,antag99/libgdx,Xhanim/libgdx,davebaol/libgdx,junkdog/libgdx,luischavez/libgdx,djom20/libgdx,curtiszimmerman/libgdx,snovak/libgdx,czyzby/libgdx,MikkelTAndersen/libgdx,PedroRomanoBarbosa/libgdx,BlueRiverInteractive/libgdx,sinistersnare/libgdx,jasonwee/libgdx,titovmaxim/libgdx,alireza-hosseini/libgdx,xoppa/libgdx,tell10glu/libgdx,mumer92/libgdx,ttencate/libgdx,yangweigbh/libgdx,snovak/libgdx,copystudy/libgdx,FredGithub/libgdx,davebaol/libgdx,Badazdz/libgdx,Thotep/libgdx,basherone/libgdxcn,Zomby2D/libgdx,stickyd/libgdx,lordjone/libgdx,1yvT0s/libgdx,mumer92/libgdx,tell10glu/libgdx,flaiker/libgdx,js78/libgdx,collinsmith/libgdx,Xhanim/libgdx,TheAks999/libgdx,gouessej/libgdx,bsmr-java/libgdx,bsmr-java/libgdx,xranby/libgdx,ricardorigodon/libgdx,katiepino/libgdx,firefly2442/libgdx,djom20/libgdx,sjosegarcia/libgdx,GreenLightning/libgdx,del-sol/libgdx,xoppa/libgdx,collinsmith/libgdx,alex-dorokhov/libgdx,tommyettinger/libgdx,kotcrab/libgdx,Thotep/libgdx,MovingBlocks/libgdx,zommuter/libgdx,1yvT0s/libgdx,309746069/libgdx,kzganesan/libgdx,flaiker/libgdx,samskivert/libgdx,azakhary/libgdx,gf11speed/libgdx,Dzamir/libgdx,GreenLightning/libgdx,shiweihappy/libgdx,gf11speed/libgdx,EsikAntony/libgdx,TheAks999/libgdx,antag99/libgdx,Zomby2D/libgdx,xpenatan/libgdx-LWJGL3,MadcowD/libgdx,noelsison2/libgdx,1yvT0s/libgdx,MovingBlocks/libgdx,SidneyXu/libgdx,titovmaxim/libgdx,MathieuDuponchelle/gdx,gouessej/libgdx,jberberick/libgdx,Senth/libgdx,ThiagoGarciaAlves/libgdx,kotcrab/libgdx,del-sol/libgdx,firefly2442/libgdx,thepullman/libgdx,toloudis/libgdx,nave966/libgdx,ya7lelkom/libgdx,xranby/libgdx,luischavez/libgdx,MadcowD/libgdx,saltares/libgdx,nudelchef/libgdx,KrisLee/libgdx,MikkelTAndersen/libgdx,flaiker/libgdx,ninoalma/libgdx,PedroRomanoBarbosa/libgdx,ThiagoGarciaAlves/libgdx,azakhary/libgdx,jasonwee/libgdx,nudelchef/libgdx,MovingBlocks/libgdx,jsjolund/libgdx,FyiurAmron/libgdx,FyiurAmron/libgdx,codepoke/libgdx,andyvand/libgdx,andyvand/libgdx,xranby/libgdx,MetSystem/libgdx,flaiker/libgdx,azakhary/libgdx,tommycli/libgdx,ninoalma/libgdx,MathieuDuponchelle/gdx,haedri/libgdx-1,srwonka/libGdx,lordjone/libgdx,kagehak/libgdx,ricardorigodon/libgdx,titovmaxim/libgdx,flaiker/libgdx,anserran/libgdx,js78/libgdx,haedri/libgdx-1,tommycli/libgdx,tommyettinger/libgdx,Dzamir/libgdx,youprofit/libgdx,revo09/libgdx,Zonglin-Li6565/libgdx,josephknight/libgdx,nrallakis/libgdx,alireza-hosseini/libgdx,azakhary/libgdx,sarkanyi/libgdx,GreenLightning/libgdx,ya7lelkom/libgdx,djom20/libgdx,fiesensee/libgdx,zhimaijoy/libgdx,anserran/libgdx,Badazdz/libgdx,Zomby2D/libgdx,titovmaxim/libgdx,Gliby/libgdx,ttencate/libgdx,js78/libgdx,curtiszimmerman/libgdx,xpenatan/libgdx-LWJGL3,js78/libgdx,nrallakis/libgdx,codepoke/libgdx,cypherdare/libgdx,srwonka/libGdx,MikkelTAndersen/libgdx,js78/libgdx,BlueRiverInteractive/libgdx,EsikAntony/libgdx,bgroenks96/libgdx,ryoenji/libgdx,nave966/libgdx,saqsun/libgdx,hyvas/libgdx,anserran/libgdx,NathanSweet/libgdx,zommuter/libgdx,kotcrab/libgdx,yangweigbh/libgdx,stinsonga/libgdx,ttencate/libgdx,FyiurAmron/libgdx,codepoke/libgdx,KrisLee/libgdx,NathanSweet/libgdx,yangweigbh/libgdx,codepoke/libgdx,billgame/libgdx,MetSystem/libgdx,toa5/libgdx,junkdog/libgdx,tommycli/libgdx,fiesensee/libgdx,EsikAntony/libgdx,zhimaijoy/libgdx,hyvas/libgdx,nelsonsilva/libgdx,saqsun/libgdx,SidneyXu/libgdx,Xhanim/libgdx,xpenatan/libgdx-LWJGL3,Wisienkas/libgdx,js78/libgdx,saltares/libgdx,ricardorigodon/libgdx,tommycli/libgdx,bgroenks96/libgdx,MadcowD/libgdx,realitix/libgdx,designcrumble/libgdx,toa5/libgdx,revo09/libgdx,GreenLightning/libgdx,toloudis/libgdx,stickyd/libgdx,toa5/libgdx,tommycli/libgdx,Gliby/libgdx,shiweihappy/libgdx,katiepino/libgdx,ryoenji/libgdx,Thotep/libgdx,MetSystem/libgdx,xpenatan/libgdx-LWJGL3,TheAks999/libgdx,JDReutt/libgdx,sjosegarcia/libgdx,Gliby/libgdx,tommycli/libgdx,FyiurAmron/libgdx,nave966/libgdx,alex-dorokhov/libgdx,nooone/libgdx,Zonglin-Li6565/libgdx,ryoenji/libgdx,xranby/libgdx,zhimaijoy/libgdx,1yvT0s/libgdx,nelsonsilva/libgdx,ztv/libgdx,srwonka/libGdx,ricardorigodon/libgdx,realitix/libgdx,nudelchef/libgdx,shiweihappy/libgdx,sarkanyi/libgdx,UnluckyNinja/libgdx,FredGithub/libgdx,MathieuDuponchelle/gdx,ThiagoGarciaAlves/libgdx,codepoke/libgdx,mumer92/libgdx,hyvas/libgdx,kzganesan/libgdx,bladecoder/libgdx,KrisLee/libgdx,snovak/libgdx,jasonwee/libgdx,gdos/libgdx,katiepino/libgdx,alireza-hosseini/libgdx,anserran/libgdx,alex-dorokhov/libgdx,jsjolund/libgdx,Badazdz/libgdx,jberberick/libgdx,petugez/libgdx,tell10glu/libgdx,fiesensee/libgdx,zhimaijoy/libgdx,toloudis/libgdx,stickyd/libgdx,ThiagoGarciaAlves/libgdx,shiweihappy/libgdx,sjosegarcia/libgdx,junkdog/libgdx,gdos/libgdx,youprofit/libgdx,ttencate/libgdx,JDReutt/libgdx,MathieuDuponchelle/gdx,UnluckyNinja/libgdx,toloudis/libgdx,josephknight/libgdx,revo09/libgdx,stickyd/libgdx,Wisienkas/libgdx,ninoalma/libgdx,junkdog/libgdx,Arcnor/libgdx,firefly2442/libgdx,MathieuDuponchelle/gdx,anserran/libgdx,MovingBlocks/libgdx,Senth/libgdx,sarkanyi/libgdx,cypherdare/libgdx,UnluckyNinja/libgdx,Senth/libgdx,josephknight/libgdx,revo09/libgdx,Deftwun/libgdx,zhimaijoy/libgdx,gdos/libgdx,katiepino/libgdx,billgame/libgdx,petugez/libgdx,js78/libgdx,tommyettinger/libgdx,1yvT0s/libgdx,realitix/libgdx,MikkelTAndersen/libgdx,kzganesan/libgdx,309746069/libgdx,saltares/libgdx,JFixby/libgdx,noelsison2/libgdx,MikkelTAndersen/libgdx,Thotep/libgdx,Dzamir/libgdx,alireza-hosseini/libgdx,jasonwee/libgdx,nave966/libgdx,haedri/libgdx-1,ryoenji/libgdx,revo09/libgdx,bsmr-java/libgdx,lordjone/libgdx,Dzamir/libgdx,luischavez/libgdx,katiepino/libgdx,ThiagoGarciaAlves/libgdx,del-sol/libgdx,katiepino/libgdx,xoppa/libgdx,ya7lelkom/libgdx,Deftwun/libgdx,sarkanyi/libgdx,Deftwun/libgdx,saqsun/libgdx,toloudis/libgdx,tommyettinger/libgdx,309746069/libgdx,Thotep/libgdx,toa5/libgdx,bsmr-java/libgdx,sarkanyi/libgdx,noelsison2/libgdx,Deftwun/libgdx,ya7lelkom/libgdx,jberberick/libgdx,TheAks999/libgdx,ztv/libgdx,TheAks999/libgdx,TheAks999/libgdx,GreenLightning/libgdx,shiweihappy/libgdx,alireza-hosseini/libgdx,czyzby/libgdx,xranby/libgdx,Zonglin-Li6565/libgdx,ricardorigodon/libgdx,Dzamir/libgdx,mumer92/libgdx,kagehak/libgdx,yangweigbh/libgdx,thepullman/libgdx,gouessej/libgdx,petugez/libgdx,kotcrab/libgdx,Xhanim/libgdx,EsikAntony/libgdx,libgdx/libgdx,czyzby/libgdx,nave966/libgdx,zommuter/libgdx,designcrumble/libgdx,sarkanyi/libgdx,revo09/libgdx,gouessej/libgdx,Arcnor/libgdx,Heart2009/libgdx,curtiszimmerman/libgdx,copystudy/libgdx,bgroenks96/libgdx,nrallakis/libgdx,fiesensee/libgdx,Senth/libgdx,Gliby/libgdx,309746069/libgdx,kagehak/libgdx,del-sol/libgdx,xranby/libgdx,UnluckyNinja/libgdx,alex-dorokhov/libgdx,saltares/libgdx,jberberick/libgdx,MathieuDuponchelle/gdx,nooone/libgdx | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.glutils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectMap;
/**
* <p>
* A shader program encapsulates a vertex and fragment shader pair linked to form a shader program useable with OpenGL ES 2.0.
* </p>
*
* <p>
* After construction a ShaderProgram can be used to draw {@link Mesh}. To make the GPU use a specific ShaderProgram the programs
* {@link ShaderProgram#begin()} method must be used which effectively binds the program.
* </p>
*
* <p>
* When a ShaderProgram is bound one can set uniforms, vertex attributes and attributes as needed via the respective methods.
* </p>
*
* <p>
* A ShaderProgram can be unbound with a call to {@link ShaderProgram#end()}
* </p>
*
* <p>
* A ShaderProgram must be disposed via a call to {@link ShaderProgram#dispose()} when it is no longer needed
* </p>
*
* <p>
* ShaderPrograms are managed. In case the OpenGL context is lost all shaders get invalidated and have to be reloaded. This
* happens on Android when a user switches to another application or receives an incoming call. Managed ShaderPrograms are
* automatically reloaded when the OpenGL context is recreated so you don't have to do this manually.
* </p>
*
* @author mzechner
*
*/
public class ShaderProgram implements Disposable {
/** flag indicating whether attributes & uniforms must be present at all times **/
public static boolean pedantic = true;
/** the list of currently available shaders **/
private final static Map<Application, List<ShaderProgram>> shaders = new HashMap<Application, List<ShaderProgram>>();
/** the log **/
private String log = "";
/** whether this program compiled succesfully **/
private boolean isCompiled;
/** uniform lookup **/
private final ObjectMap<String, Integer> uniforms = new ObjectMap<String, Integer>();
/** uniform types **/
private final ObjectMap<String, Integer> uniformTypes = new ObjectMap<String, Integer>();
/** uniform names **/
private String[] uniformNames;
/** attribute lookup **/
private final ObjectMap<String, Integer> attributes = new ObjectMap<String, Integer>();
/** attribute types **/
private final ObjectMap<String, Integer> attributeTypes = new ObjectMap<String, Integer>();
/** attribute names **/
private String[] attributeNames;
/** program handle **/
private int program;
/** vertex shader handle **/
private int vertexShaderHandle;
/** fragment shader handle **/
private int fragmentShaderHandle;
/** matrix float buffer **/
private final FloatBuffer matrix;
/** vertex shader source **/
private final String vertexShaderSource;
/** fragment shader source **/
private final String fragmentShaderSource;
/** whether this shader was invalidated **/
private boolean invalidated;
/** direct buffer for passing float and int uniform arrays **/
private ByteBuffer buffer = null;
private FloatBuffer floatBuffer = null;
private IntBuffer intBuffer = null;
/**
* Construcs a new JOglShaderProgram and immediatly compiles it.
*
* @param vertexShader the vertex shader
* @param fragmentShader the fragment shader
*/
public ShaderProgram (String vertexShader, String fragmentShader) {
if (vertexShader == null) throw new IllegalArgumentException("vertex shader must not be null");
if (fragmentShader == null) throw new IllegalArgumentException("fragment shader must not be null");
this.vertexShaderSource = vertexShader;
this.fragmentShaderSource = fragmentShader;
this.matrix = BufferUtils.newFloatBuffer(16);
compileShaders(vertexShader, fragmentShader);
if(isCompiled()) {
// fetchAttributes();
// fetchUniforms();
addManagedShader(Gdx.app, this);
}
}
/**
* Loads and compiles the shaders, creates a new program and links the shaders.
*
* @param vertexShader
* @param fragmentShader
*/
private void compileShaders (String vertexShader, String fragmentShader) {
vertexShaderHandle = loadShader(GL20.GL_VERTEX_SHADER, vertexShader);
fragmentShaderHandle = loadShader(GL20.GL_FRAGMENT_SHADER, fragmentShader);
if (vertexShaderHandle == -1 || fragmentShaderHandle == -1) {
isCompiled = false;
return;
}
program = linkProgram();
if (program == -1) {
isCompiled = false;
return;
}
isCompiled = true;
}
private int loadShader (int type, String source) {
GL20 gl = Gdx.graphics.getGL20();
ByteBuffer tmp = ByteBuffer.allocateDirect(4);
tmp.order(ByteOrder.nativeOrder());
IntBuffer intbuf = tmp.asIntBuffer();
int shader = gl.glCreateShader(type);
if (shader == 0) return -1;
gl.glShaderSource(shader, source);
gl.glCompileShader(shader);
gl.glGetShaderiv(shader, GL20.GL_COMPILE_STATUS, intbuf);
int compiled = intbuf.get(0);
if (compiled == 0) {
gl.glGetShaderiv(shader, GL20.GL_INFO_LOG_LENGTH, intbuf);
int infoLogLength = intbuf.get(0);
if (infoLogLength > 1) {
String infoLog = gl.glGetShaderInfoLog(shader);
log += infoLog;
}
return -1;
}
return shader;
}
private int linkProgram () {
GL20 gl = Gdx.graphics.getGL20();
int program = gl.glCreateProgram();
if (program == 0) return -1;
gl.glAttachShader(program, vertexShaderHandle);
gl.glAttachShader(program, fragmentShaderHandle);
gl.glLinkProgram(program);
ByteBuffer tmp = ByteBuffer.allocateDirect(4);
tmp.order(ByteOrder.nativeOrder());
IntBuffer intbuf = tmp.asIntBuffer();
gl.glGetProgramiv(program, GL20.GL_LINK_STATUS, intbuf);
int linked = intbuf.get(0);
if (linked == 0) {
return -1;
}
return program;
}
final static IntBuffer intbuf = BufferUtils.newIntBuffer(1);
/**
* @return the log info for the shader compilation and program linking stage. The shader needs to be bound for this
* method to have an effect.
*/
public String getLog () {
if(isCompiled) {
Gdx.gl20.glGetProgramiv(program, GL20.GL_INFO_LOG_LENGTH, intbuf);
int infoLogLength = intbuf.get(0);
if (infoLogLength > 1) log = Gdx.gl20.glGetProgramInfoLog(program);
return log;
} else {
return log;
}
}
/**
* @return whether this ShaderProgram compiled successfully.
*/
public boolean isCompiled () {
return isCompiled;
}
private int fetchAttributeLocation (String name) {
GL20 gl = Gdx.graphics.getGL20();
Integer location;
if ((location = attributes.get(name)) == null) {
location = gl.glGetAttribLocation(program, name);
if (location != -1) attributes.put(name, location);
}
return location;
}
private int fetchUniformLocation (String name) {
GL20 gl = Gdx.graphics.getGL20();
Integer location;
if ((location = uniforms.get(name)) == null) {
location = gl.glGetUniformLocation(program, name);
if (location == -1 && pedantic) throw new IllegalArgumentException("no uniform with name '" + name + "' in shader");
uniforms.put(name, location);
}
return location;
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value the value
*/
public void setUniformi (String name, int value) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform1i(location, value);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
*/
public void setUniformi (String name, int value1, int value2) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform2i(location, value1, value2);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
*/
public void setUniformi (String name, int value1, int value2, int value3) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform3i(location, value1, value2, value3);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
* @param value4 the fourth value
*/
public void setUniformi (String name, int value1, int value2, int value3, int value4) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform4i(location, value1, value2, value3, value4);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value the value
*/
public void setUniformf (String name, float value) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform1f(location, value);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
*/
public void setUniformf (String name, float value1, float value2) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform2f(location, value1, value2);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
*/
public void setUniformf (String name, float value1, float value2, float value3) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform3f(location, value1, value2, value3);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
* @param value4 the fourth value
*/
public void setUniformf (String name, float value1, float value2, float value3, float value4) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform4f(location, value1, value2, value3, value4);
}
public void setUniform1fv(String name, float[] values, int offset, int length) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
ensureBufferCapacity(length << 2);
floatBuffer.clear();
BufferUtils.copy(values, floatBuffer, length, offset);
gl.glUniform1fv(location, length, floatBuffer);
}
public void setUniform2fv(String name, float[] values, int offset, int length) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
ensureBufferCapacity(length << 2);
floatBuffer.clear();
BufferUtils.copy(values, floatBuffer, length, offset);
gl.glUniform2fv(location, length / 2, floatBuffer);
}
public void setUniform3fv(String name, float[] values, int offset, int length) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
ensureBufferCapacity(length << 2);
floatBuffer.clear();
BufferUtils.copy(values, floatBuffer, length, offset);
gl.glUniform3fv(location, length / 3, floatBuffer);
}
public void setUniform4fv(String name, float[] values, int offset, int length) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
ensureBufferCapacity(length << 2);
floatBuffer.clear();
BufferUtils.copy(values, floatBuffer, length, offset);
gl.glUniform4fv(location, length / 4, floatBuffer);
}
/**
* Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param matrix the matrix
*/
public void setUniformMatrix (String name, Matrix4 matrix) {
setUniformMatrix(name, matrix, false);
}
/**
* Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param matrix the matrix
* @param transpose whether the matrix shouls be transposed
*/
public void setUniformMatrix (String name, Matrix4 matrix, boolean transpose) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
this.matrix.clear();
BufferUtils.copy(matrix.val, this.matrix, matrix.val.length, 0);
gl.glUniformMatrix4fv(location, 1, transpose, this.matrix);
}
/**
* Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param matrix the matrix
*/
public void setUniformMatrix (String name, Matrix3 matrix) {
setUniformMatrix(name, matrix, false);
}
/**
* Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param matrix the matrix
* @param transpose whether the uniform matrix should be transposed
*/
public void setUniformMatrix (String name, Matrix3 matrix, boolean transpose) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
float[] vals = matrix.getValues();
this.matrix.clear();
BufferUtils.copy(vals, this.matrix, vals.length, 0);
gl.glUniformMatrix3fv(location, 1, transpose, this.matrix);
}
/**
* Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the attribute name
* @param size the number of components, must be >= 1 and <= 4
* @param type the type, must be one of GL20.GL_BYTE, GL20.GL_UNSIGNED_BYTE, GL20.GL_SHORT,
* GL20.GL_UNSIGNED_SHORT,GL20.GL_FIXED, or GL20.GL_FLOAT. GL_FIXED will not work on the desktop
* @param normalize whether fixed point data should be normalized. Will not work on the desktop
* @param stride the stride in bytes between successive attributes
* @param buffer the buffer containing the vertex attributes.
*/
public void setVertexAttribute (String name, int size, int type, boolean normalize, int stride, FloatBuffer buffer) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchAttributeLocation(name);
gl.glVertexAttribPointer(location, size, type, normalize, stride, buffer);
}
/**
* Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the attribute name
* @param size the number of components, must be >= 1 and <= 4
* @param type the type, must be one of GL20.GL_BYTE, GL20.GL_UNSIGNED_BYTE, GL20.GL_SHORT,
* GL20.GL_UNSIGNED_SHORT,GL20.GL_FIXED, or GL20.GL_FLOAT. GL_FIXED will not work on the desktop
* @param normalize whether fixed point data should be normalized. Will not work on the desktop
* @param stride the stride in bytes between successive attributes
* @param offset byte offset into the vertex buffer object bound to GL20.GL_ARRAY_BUFFER.
*/
public void setVertexAttribute (String name, int size, int type, boolean normalize, int stride, int offset) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchAttributeLocation(name);
if (location == -1) return;
gl.glVertexAttribPointer(location, size, type, normalize, stride, offset);
}
/**
* Makes OpenGL ES 2.0 use this vertex and fragment shader pair. When you are done with this shader you have to call
* {@link ShaderProgram#end()}.
*/
public void begin () {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
gl.glUseProgram(program);
}
/**
* Disables this shader. Must be called when one is done with the shader. Don't mix it with dispose, that will release the
* shader resources.
*/
public void end () {
GL20 gl = Gdx.graphics.getGL20();
gl.glUseProgram(0);
}
/**
* Disposes all resources associated with this shader. Must be called when the shader is no longer used.
*/
public void dispose () {
GL20 gl = Gdx.graphics.getGL20();
gl.glUseProgram(0);
gl.glDeleteShader(vertexShaderHandle);
gl.glDeleteShader(fragmentShaderHandle);
gl.glDeleteProgram(program);
if(shaders.get(Gdx.app) != null) shaders.get(Gdx.app).remove(this);
}
/**
* Disables the vertex attribute with the given name
*
* @param name the vertex attribute name
*/
public void disableVertexAttribute (String name) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchAttributeLocation(name);
if (location == -1) return;
gl.glDisableVertexAttribArray(location);
}
/**
* Enables the vertex attribute with the given name
*
* @param name the vertex attribute name
*/
public void enableVertexAttribute (String name) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchAttributeLocation(name);
if (location == -1) return;
gl.glEnableVertexAttribArray(location);
}
private void checkManaged () {
if (invalidated) {
compileShaders(vertexShaderSource, fragmentShaderSource);
invalidated = false;
}
}
private void addManagedShader (Application app, ShaderProgram shaderProgram) {
List<ShaderProgram> managedResources = shaders.get(app);
if(managedResources == null) managedResources = new ArrayList<ShaderProgram>();
managedResources.add(shaderProgram);
shaders.put(app, managedResources);
}
/**
* Invalidates all shaders so the next time they are used new handles are generated
* @param app
*/
public static void invalidateAllShaderPrograms (Application app) {
if (Gdx.graphics.getGL20() == null) return;
List<ShaderProgram> shaderList = shaders.get(app);
if(shaderList == null) return;
for (int i = 0; i < shaderList.size(); i++) {
shaderList.get(i).invalidated = true;
shaderList.get(i).checkManaged();
}
}
public static void clearAllShaderPrograms (Application app) {
shaders.remove(app);
}
public static String getManagedStatus() {
StringBuilder builder = new StringBuilder();
int i = 0;
builder.append("Managed shaders/app: { ");
for(Application app: shaders.keySet()) {
builder.append(shaders.get(app).size());
builder.append(" ");
}
builder.append("}");
return builder.toString();
}
/**
* Sets the given attribute
*
* @param name the name of the attribute
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
* @param value4 the fourth value
*/
public void setAttributef (String name, float value1, float value2, float value3, float value4) {
GL20 gl = Gdx.graphics.getGL20();
int location = fetchAttributeLocation(name);
gl.glVertexAttrib4f(location, value1, value2, value3, value4);
}
private void ensureBufferCapacity(int numBytes) {
if(buffer == null || buffer.capacity() != numBytes) {
buffer = BufferUtils.newByteBuffer(numBytes);
floatBuffer = buffer.asFloatBuffer();
intBuffer = buffer.asIntBuffer();
}
}
IntBuffer params = BufferUtils.newIntBuffer(1);
IntBuffer type = BufferUtils.newIntBuffer(1);
private void fetchUniforms() {
params.clear();
Gdx.gl20.glGetProgramiv(program, GL20.GL_ACTIVE_UNIFORMS, params);
int numUniforms = params.get(0);
uniformNames = new String[numUniforms];
for(int i = 0; i < numUniforms; i++) {
params.clear();
params.put(0, 256);
type.clear();
String name = Gdx.gl20.glGetActiveUniform(program, i, params, type);
int location = Gdx.gl20.glGetUniformLocation(program, name);
uniforms.put(name, location);
uniformTypes.put(name, type.get(0));
uniformNames[i] = name;
}
}
private void fetchAttributes() {
params.clear();
Gdx.gl20.glGetProgramiv(program, GL20.GL_ACTIVE_ATTRIBUTES, params);
int numAttributes = params.get(0);
attributeNames = new String[numAttributes];
for(int i = 0; i < numAttributes; i++) {
params.clear();
params.put(0, 256);
type.clear();
String name = Gdx.gl20.glGetActiveAttrib(program, i, params, type);
int location = Gdx.gl20.glGetAttribLocation(program, name);
attributes.put(name, location);
attributeTypes.put(name, type.get(0));
attributeNames[i] = name;
}
}
/**
* @param name the name of the attribute
* @return whether the attribute is available in the shader
*/
public boolean hasAttribute(String name) {
return attributes.containsKey(name);
}
/**
* @param name the name of the attribute
* @return the type of the attribute, one of {@link GL20#GL_FLOAT}, {@link GL20#GL_FLOAT_VEC2} etc.
*/
public int getAttributeType(String name) {
Integer type = attributes.get(name);
if(type == null) return 0;
else return type;
}
/**
* @param name the name of the attribute
* @return the location of the attribute or -1.
*/
public int getAttributeLocation(String name) {
Integer location = attributes.get(name);
if(location == null) return -1;
else return location;
}
/**
* @param name the name of the uniform
* @return whether the uniform is available in the shader
*/
public boolean hasUniform(String name) {
return uniforms.containsKey(name);
}
/**
* @param name the name of the uniform
* @return the type of the uniform, one of {@link GL20#GL_FLOAT}, {@link GL20#GL_FLOAT_VEC2} etc.
*/
public int getUniformType(String name) {
Integer type = attributes.get(name);
if(type == null) return 0;
else return type;
}
/**
* @param name the name of the uniform
* @return the location of the uniform or -1.
*/
public int getUniformLocation(String name) {
Integer location = uniforms.get(name);
if(location == null) return -1;
else return location;
}
/**
* @return the attributes
*/
public String[] getAttributes() {
return attributeNames;
}
/**
* @return the uniforms
*/
public String[] getUniforms() {
return uniformNames;
}
} | gdx/src/com/badlogic/gdx/graphics/glutils/ShaderProgram.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.glutils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectMap;
/**
* <p>
* A shader program encapsulates a vertex and fragment shader pair linked to form a shader program useable with OpenGL ES 2.0.
* </p>
*
* <p>
* After construction a ShaderProgram can be used to draw {@link Mesh}. To make the GPU use a specific ShaderProgram the programs
* {@link ShaderProgram#begin()} method must be used which effectively binds the program.
* </p>
*
* <p>
* When a ShaderProgram is bound one can set uniforms, vertex attributes and attributes as needed via the respective methods.
* </p>
*
* <p>
* A ShaderProgram can be unbound with a call to {@link ShaderProgram#end()}
* </p>
*
* <p>
* A ShaderProgram must be disposed via a call to {@link ShaderProgram#dispose()} when it is no longer needed
* </p>
*
* <p>
* ShaderPrograms are managed. In case the OpenGL context is lost all shaders get invalidated and have to be reloaded. This
* happens on Android when a user switches to another application or receives an incoming call. Managed ShaderPrograms are
* automatically reloaded when the OpenGL context is recreated so you don't have to do this manually.
* </p>
*
* @author mzechner
*
*/
public class ShaderProgram implements Disposable {
/** flag indicating whether attributes & uniforms must be present at all times **/
public static boolean pedantic = true;
/** the list of currently available shaders **/
private final static Map<Application, List<ShaderProgram>> shaders = new HashMap<Application, List<ShaderProgram>>();
/** the log **/
private String log = "";
/** whether this program compiled succesfully **/
private boolean isCompiled;
/** uniform lookup **/
private final ObjectMap<String, Integer> uniforms = new ObjectMap<String, Integer>();
/** attribute lookup **/
private final ObjectMap<String, Integer> attributes = new ObjectMap<String, Integer>();
/** program handle **/
private int program;
/** vertex shader handle **/
private int vertexShaderHandle;
/** fragment shader handle **/
private int fragmentShaderHandle;
/** matrix float buffer **/
private final FloatBuffer matrix;
/** vertex shader source **/
private final String vertexShaderSource;
/** fragment shader source **/
private final String fragmentShaderSource;
/** whether this shader was invalidated **/
private boolean invalidated;
/** direct buffer for passing float and int uniform arrays **/
private ByteBuffer buffer = null;
private FloatBuffer floatBuffer = null;
private IntBuffer intBuffer = null;
/**
* Construcs a new JOglShaderProgram and immediatly compiles it.
*
* @param vertexShader the vertex shader
* @param fragmentShader the fragment shader
*/
public ShaderProgram (String vertexShader, String fragmentShader) {
if (vertexShader == null) throw new IllegalArgumentException("vertex shader must not be null");
if (fragmentShader == null) throw new IllegalArgumentException("fragment shader must not be null");
this.vertexShaderSource = vertexShader;
this.fragmentShaderSource = fragmentShader;
this.matrix = BufferUtils.newFloatBuffer(16);
compileShaders(vertexShader, fragmentShader);
if(isCompiled()) {
// fetchAttributes();
// fetchUniforms();
addManagedShader(Gdx.app, this);
}
}
/**
* Loads and compiles the shaders, creates a new program and links the shaders.
*
* @param vertexShader
* @param fragmentShader
*/
private void compileShaders (String vertexShader, String fragmentShader) {
vertexShaderHandle = loadShader(GL20.GL_VERTEX_SHADER, vertexShader);
fragmentShaderHandle = loadShader(GL20.GL_FRAGMENT_SHADER, fragmentShader);
if (vertexShaderHandle == -1 || fragmentShaderHandle == -1) {
isCompiled = false;
return;
}
program = linkProgram();
if (program == -1) {
isCompiled = false;
return;
}
isCompiled = true;
}
private int loadShader (int type, String source) {
GL20 gl = Gdx.graphics.getGL20();
ByteBuffer tmp = ByteBuffer.allocateDirect(4);
tmp.order(ByteOrder.nativeOrder());
IntBuffer intbuf = tmp.asIntBuffer();
int shader = gl.glCreateShader(type);
if (shader == 0) return -1;
gl.glShaderSource(shader, source);
gl.glCompileShader(shader);
gl.glGetShaderiv(shader, GL20.GL_COMPILE_STATUS, intbuf);
int compiled = intbuf.get(0);
if (compiled == 0) {
gl.glGetShaderiv(shader, GL20.GL_INFO_LOG_LENGTH, intbuf);
int infoLogLength = intbuf.get(0);
if (infoLogLength > 1) {
String infoLog = gl.glGetShaderInfoLog(shader);
log += infoLog;
}
return -1;
}
return shader;
}
private int linkProgram () {
GL20 gl = Gdx.graphics.getGL20();
int program = gl.glCreateProgram();
if (program == 0) return -1;
gl.glAttachShader(program, vertexShaderHandle);
gl.glAttachShader(program, fragmentShaderHandle);
gl.glLinkProgram(program);
ByteBuffer tmp = ByteBuffer.allocateDirect(4);
tmp.order(ByteOrder.nativeOrder());
IntBuffer intbuf = tmp.asIntBuffer();
gl.glGetProgramiv(program, GL20.GL_LINK_STATUS, intbuf);
int linked = intbuf.get(0);
if (linked == 0) {
return -1;
}
return program;
}
final static IntBuffer intbuf = BufferUtils.newIntBuffer(1);
/**
* @return the log info for the shader compilation and program linking stage. The shader needs to be bound for this
* method to have an effect.
*/
public String getLog () {
if(isCompiled) {
Gdx.gl20.glGetProgramiv(program, GL20.GL_INFO_LOG_LENGTH, intbuf);
int infoLogLength = intbuf.get(0);
if (infoLogLength > 1) log = Gdx.gl20.glGetProgramInfoLog(program);
return log;
} else {
return log;
}
}
/**
* @return whether this ShaderProgram compiled successfully.
*/
public boolean isCompiled () {
return isCompiled;
}
private int fetchAttributeLocation (String name) {
GL20 gl = Gdx.graphics.getGL20();
Integer location;
if ((location = attributes.get(name)) == null) {
location = gl.glGetAttribLocation(program, name);
if (location != -1) attributes.put(name, location);
}
return location;
}
private int fetchUniformLocation (String name) {
GL20 gl = Gdx.graphics.getGL20();
Integer location;
if ((location = uniforms.get(name)) == null) {
location = gl.glGetUniformLocation(program, name);
if (location == -1 && pedantic) throw new IllegalArgumentException("no uniform with name '" + name + "' in shader");
uniforms.put(name, location);
}
return location;
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value the value
*/
public void setUniformi (String name, int value) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform1i(location, value);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
*/
public void setUniformi (String name, int value1, int value2) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform2i(location, value1, value2);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
*/
public void setUniformi (String name, int value1, int value2, int value3) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform3i(location, value1, value2, value3);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
* @param value4 the fourth value
*/
public void setUniformi (String name, int value1, int value2, int value3, int value4) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform4i(location, value1, value2, value3, value4);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value the value
*/
public void setUniformf (String name, float value) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform1f(location, value);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
*/
public void setUniformf (String name, float value1, float value2) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform2f(location, value1, value2);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
*/
public void setUniformf (String name, float value1, float value2, float value3) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform3f(location, value1, value2, value3);
}
/**
* Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
* @param value4 the fourth value
*/
public void setUniformf (String name, float value1, float value2, float value3, float value4) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
gl.glUniform4f(location, value1, value2, value3, value4);
}
public void setUniform1fv(String name, float[] values, int offset, int length) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
ensureBufferCapacity(length << 2);
floatBuffer.clear();
BufferUtils.copy(values, floatBuffer, length, offset);
gl.glUniform1fv(location, length, floatBuffer);
}
public void setUniform2fv(String name, float[] values, int offset, int length) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
ensureBufferCapacity(length << 2);
floatBuffer.clear();
BufferUtils.copy(values, floatBuffer, length, offset);
gl.glUniform2fv(location, length / 2, floatBuffer);
}
public void setUniform3fv(String name, float[] values, int offset, int length) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
ensureBufferCapacity(length << 2);
floatBuffer.clear();
BufferUtils.copy(values, floatBuffer, length, offset);
gl.glUniform3fv(location, length / 3, floatBuffer);
}
public void setUniform4fv(String name, float[] values, int offset, int length) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
ensureBufferCapacity(length << 2);
floatBuffer.clear();
BufferUtils.copy(values, floatBuffer, length, offset);
gl.glUniform4fv(location, length / 4, floatBuffer);
}
/**
* Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param matrix the matrix
*/
public void setUniformMatrix (String name, Matrix4 matrix) {
setUniformMatrix(name, matrix, false);
}
/**
* Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param matrix the matrix
* @param transpose whether the matrix shouls be transposed
*/
public void setUniformMatrix (String name, Matrix4 matrix, boolean transpose) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
this.matrix.clear();
BufferUtils.copy(matrix.val, this.matrix, matrix.val.length, 0);
gl.glUniformMatrix4fv(location, 1, transpose, this.matrix);
}
/**
* Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param matrix the matrix
*/
public void setUniformMatrix (String name, Matrix3 matrix) {
setUniformMatrix(name, matrix, false);
}
/**
* Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the name of the uniform
* @param matrix the matrix
* @param transpose whether the uniform matrix should be transposed
*/
public void setUniformMatrix (String name, Matrix3 matrix, boolean transpose) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchUniformLocation(name);
float[] vals = matrix.getValues();
this.matrix.clear();
BufferUtils.copy(vals, this.matrix, vals.length, 0);
gl.glUniformMatrix3fv(location, 1, transpose, this.matrix);
}
/**
* Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the attribute name
* @param size the number of components, must be >= 1 and <= 4
* @param type the type, must be one of GL20.GL_BYTE, GL20.GL_UNSIGNED_BYTE, GL20.GL_SHORT,
* GL20.GL_UNSIGNED_SHORT,GL20.GL_FIXED, or GL20.GL_FLOAT. GL_FIXED will not work on the desktop
* @param normalize whether fixed point data should be normalized. Will not work on the desktop
* @param stride the stride in bytes between successive attributes
* @param buffer the buffer containing the vertex attributes.
*/
public void setVertexAttribute (String name, int size, int type, boolean normalize, int stride, FloatBuffer buffer) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchAttributeLocation(name);
gl.glVertexAttribPointer(location, size, type, normalize, stride, buffer);
}
/**
* Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case it is not called in between a
* {@link #begin()}/{@link #end()} block.
*
* @param name the attribute name
* @param size the number of components, must be >= 1 and <= 4
* @param type the type, must be one of GL20.GL_BYTE, GL20.GL_UNSIGNED_BYTE, GL20.GL_SHORT,
* GL20.GL_UNSIGNED_SHORT,GL20.GL_FIXED, or GL20.GL_FLOAT. GL_FIXED will not work on the desktop
* @param normalize whether fixed point data should be normalized. Will not work on the desktop
* @param stride the stride in bytes between successive attributes
* @param offset byte offset into the vertex buffer object bound to GL20.GL_ARRAY_BUFFER.
*/
public void setVertexAttribute (String name, int size, int type, boolean normalize, int stride, int offset) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchAttributeLocation(name);
if (location == -1) return;
gl.glVertexAttribPointer(location, size, type, normalize, stride, offset);
}
/**
* Makes OpenGL ES 2.0 use this vertex and fragment shader pair. When you are done with this shader you have to call
* {@link ShaderProgram#end()}.
*/
public void begin () {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
gl.glUseProgram(program);
}
/**
* Disables this shader. Must be called when one is done with the shader. Don't mix it with dispose, that will release the
* shader resources.
*/
public void end () {
GL20 gl = Gdx.graphics.getGL20();
gl.glUseProgram(0);
}
/**
* Disposes all resources associated with this shader. Must be called when the shader is no longer used.
*/
public void dispose () {
GL20 gl = Gdx.graphics.getGL20();
gl.glUseProgram(0);
gl.glDeleteShader(vertexShaderHandle);
gl.glDeleteShader(fragmentShaderHandle);
gl.glDeleteProgram(program);
if(shaders.get(Gdx.app) != null) shaders.get(Gdx.app).remove(this);
}
/**
* Disables the vertex attribute with the given name
*
* @param name the vertex attribute name
*/
public void disableVertexAttribute (String name) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchAttributeLocation(name);
if (location == -1) return;
gl.glDisableVertexAttribArray(location);
}
/**
* Enables the vertex attribute with the given name
*
* @param name the vertex attribute name
*/
public void enableVertexAttribute (String name) {
GL20 gl = Gdx.graphics.getGL20();
checkManaged();
int location = fetchAttributeLocation(name);
if (location == -1) return;
gl.glEnableVertexAttribArray(location);
}
private void checkManaged () {
if (invalidated) {
compileShaders(vertexShaderSource, fragmentShaderSource);
invalidated = false;
}
}
private void addManagedShader (Application app, ShaderProgram shaderProgram) {
List<ShaderProgram> managedResources = shaders.get(app);
if(managedResources == null) managedResources = new ArrayList<ShaderProgram>();
managedResources.add(shaderProgram);
shaders.put(app, managedResources);
}
/**
* Invalidates all shaders so the next time they are used new handles are generated
* @param app
*/
public static void invalidateAllShaderPrograms (Application app) {
if (Gdx.graphics.getGL20() == null) return;
List<ShaderProgram> shaderList = shaders.get(app);
if(shaderList == null) return;
for (int i = 0; i < shaderList.size(); i++) {
shaderList.get(i).invalidated = true;
shaderList.get(i).checkManaged();
}
}
public static void clearAllShaderPrograms (Application app) {
shaders.remove(app);
}
public static String getManagedStatus() {
StringBuilder builder = new StringBuilder();
int i = 0;
builder.append("Managed shaders/app: { ");
for(Application app: shaders.keySet()) {
builder.append(shaders.get(app).size());
builder.append(" ");
}
builder.append("}");
return builder.toString();
}
/**
* Sets the given attribute
*
* @param name the name of the attribute
* @param value1 the first value
* @param value2 the second value
* @param value3 the third value
* @param value4 the fourth value
*/
public void setAttributef (String name, float value1, float value2, float value3, float value4) {
GL20 gl = Gdx.graphics.getGL20();
int location = fetchAttributeLocation(name);
gl.glVertexAttrib4f(location, value1, value2, value3, value4);
}
private void ensureBufferCapacity(int numBytes) {
if(buffer == null || buffer.capacity() != numBytes) {
buffer = BufferUtils.newByteBuffer(numBytes);
floatBuffer = buffer.asFloatBuffer();
intBuffer = buffer.asIntBuffer();
}
}
IntBuffer params = BufferUtils.newIntBuffer(1);
IntBuffer type = BufferUtils.newIntBuffer(1);
private void fetchUniforms() {
params.clear();
Gdx.gl20.glGetProgramiv(program, GL20.GL_ACTIVE_UNIFORMS, params);
int numAttributes = params.get(0);
for(int i = 0; i < numAttributes; i++) {
params.clear();
params.put(0, 256);
type.clear();
String name = Gdx.gl20.glGetActiveUniform(program, i, params, type);
int location = Gdx.gl20.glGetUniformLocation(program, name);
uniforms.put(name, location);
}
}
private void fetchAttributes() {
params.clear();
Gdx.gl20.glGetProgramiv(program, GL20.GL_ACTIVE_ATTRIBUTES, params);
int numAttributes = params.get(0);
for(int i = 0; i < numAttributes; i++) {
params.clear();
params.put(0, 256);
type.clear();
String name = Gdx.gl20.glGetActiveAttrib(program, i, params, type);
int location = Gdx.gl20.glGetAttribLocation(program, name);
attributes.put(name, location);
}
}
} | [added] ShaderProgram query methods to get info on attributes and uniforms (name, location, type).
| gdx/src/com/badlogic/gdx/graphics/glutils/ShaderProgram.java | [added] ShaderProgram query methods to get info on attributes and uniforms (name, location, type). | <ide><path>dx/src/com/badlogic/gdx/graphics/glutils/ShaderProgram.java
<ide>
<ide> /** whether this program compiled succesfully **/
<ide> private boolean isCompiled;
<del>
<add>
<ide> /** uniform lookup **/
<ide> private final ObjectMap<String, Integer> uniforms = new ObjectMap<String, Integer>();
<ide>
<add> /** uniform types **/
<add> private final ObjectMap<String, Integer> uniformTypes = new ObjectMap<String, Integer>();
<add>
<add> /** uniform names **/
<add> private String[] uniformNames;
<add>
<ide> /** attribute lookup **/
<ide> private final ObjectMap<String, Integer> attributes = new ObjectMap<String, Integer>();
<add>
<add> /** attribute types **/
<add> private final ObjectMap<String, Integer> attributeTypes = new ObjectMap<String, Integer>();
<add>
<add> /** attribute names **/
<add> private String[] attributeNames;
<ide>
<ide> /** program handle **/
<ide> private int program;
<ide> private void fetchUniforms() {
<ide> params.clear();
<ide> Gdx.gl20.glGetProgramiv(program, GL20.GL_ACTIVE_UNIFORMS, params);
<del> int numAttributes = params.get(0);
<add> int numUniforms = params.get(0);
<ide>
<del> for(int i = 0; i < numAttributes; i++) {
<add> uniformNames = new String[numUniforms];
<add>
<add> for(int i = 0; i < numUniforms; i++) {
<ide> params.clear();
<ide> params.put(0, 256);
<ide> type.clear();
<ide> String name = Gdx.gl20.glGetActiveUniform(program, i, params, type);
<ide> int location = Gdx.gl20.glGetUniformLocation(program, name);
<ide> uniforms.put(name, location);
<add> uniformTypes.put(name, type.get(0));
<add> uniformNames[i] = name;
<ide> }
<ide> }
<ide>
<ide> params.clear();
<ide> Gdx.gl20.glGetProgramiv(program, GL20.GL_ACTIVE_ATTRIBUTES, params);
<ide> int numAttributes = params.get(0);
<del>
<add>
<add> attributeNames = new String[numAttributes];
<add>
<ide> for(int i = 0; i < numAttributes; i++) {
<ide> params.clear();
<ide> params.put(0, 256);
<ide> String name = Gdx.gl20.glGetActiveAttrib(program, i, params, type);
<ide> int location = Gdx.gl20.glGetAttribLocation(program, name);
<ide> attributes.put(name, location);
<add> attributeTypes.put(name, type.get(0));
<add> attributeNames[i] = name;
<ide> }
<ide> }
<add>
<add> /**
<add> * @param name the name of the attribute
<add> * @return whether the attribute is available in the shader
<add> */
<add> public boolean hasAttribute(String name) {
<add> return attributes.containsKey(name);
<add> }
<add>
<add> /**
<add> * @param name the name of the attribute
<add> * @return the type of the attribute, one of {@link GL20#GL_FLOAT}, {@link GL20#GL_FLOAT_VEC2} etc.
<add> */
<add> public int getAttributeType(String name) {
<add> Integer type = attributes.get(name);
<add> if(type == null) return 0;
<add> else return type;
<add> }
<add>
<add> /**
<add> * @param name the name of the attribute
<add> * @return the location of the attribute or -1.
<add> */
<add> public int getAttributeLocation(String name) {
<add> Integer location = attributes.get(name);
<add> if(location == null) return -1;
<add> else return location;
<add> }
<add>
<add> /**
<add> * @param name the name of the uniform
<add> * @return whether the uniform is available in the shader
<add> */
<add> public boolean hasUniform(String name) {
<add> return uniforms.containsKey(name);
<add> }
<add>
<add> /**
<add> * @param name the name of the uniform
<add> * @return the type of the uniform, one of {@link GL20#GL_FLOAT}, {@link GL20#GL_FLOAT_VEC2} etc.
<add> */
<add> public int getUniformType(String name) {
<add> Integer type = attributes.get(name);
<add> if(type == null) return 0;
<add> else return type;
<add> }
<add>
<add> /**
<add> * @param name the name of the uniform
<add> * @return the location of the uniform or -1.
<add> */
<add> public int getUniformLocation(String name) {
<add> Integer location = uniforms.get(name);
<add> if(location == null) return -1;
<add> else return location;
<add> }
<add>
<add> /**
<add> * @return the attributes
<add> */
<add> public String[] getAttributes() {
<add> return attributeNames;
<add> }
<add>
<add> /**
<add> * @return the uniforms
<add> */
<add> public String[] getUniforms() {
<add> return uniformNames;
<add> }
<ide> } |
|
JavaScript | apache-2.0 | f470d1fa44e8691ac7ce91c396c2c1d3448f91c9 | 0 | easilyBaffled/react-engine,joshbedo/react-engine,reggi/react-engine,erikakers/react-engine,samuelcouch/react-engine,imranolas/react-engine,joshbedo/react-engine,HorizonXP/react-engine,ghondar/react-engine,paypal/react-engine,dongguangming/react-engine,erikakers/react-engine,ghondar/react-engine,easilyBaffled/react-engine,skarflacka/react-engine,slkuo230/react-engine,HorizonXP/react-engine,vuhwang/react-engine,chunkiat82/react-engine,masotime/react-engine,samuelcouch/react-engine,reggi/react-engine,samsel/react-engine,skarflacka/react-engine,imranolas/react-engine,masotime/react-engine,dongguangming/react-engine | /*-------------------------------------------------------------------------------------------------------------------*\
| Copyright (C) 2015 PayPal |
| |
| Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance |
| with the License. |
| |
| You may obtain a copy of the License at |
| |
| http://www.apache.org/licenses/LICENSE-2.0 |
| |
| Unless required by applicable law or agreed to in writing, software distributed under the License is distributed |
| on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for |
| the specific language governing permissions and limitations under the License. |
\*-------------------------------------------------------------------------------------------------------------------*/
'use strict';
var util = require('./util');
var Config = require('./config');
var format = require('util').format;
var omit = require('lodash-node/compat/object/omit');
var merge = require('lodash-node/compat/object/merge');
// safely require the peer-dependencies
var React = util.safeRequire('react');
var Router = util.safeRequire('react-router');
// a template of the `script` tag that gets
// injected into the server rendered pages.
var TEMPLATE = '<script id="%s" type="application/javascript">window._store = %s;</script>';
exports.create = function create(createOptions) {
createOptions = createOptions || {};
// the render implementation
return function render(thing, options, callback) {
var routes;
function done(err, html) {
if (options.settings.env === 'development') {
// remove all the files under the express's view folder from require cache.
// Helps in making changes to react views without restarting the server.
util.clearRequireCache(createOptions.reactRoutes);
util.clearRequireCacheInDir(options.settings.views, options.settings['view engine']);
}
callback(err, html);
}
if (createOptions.reactRoutes) {
routes = require(createOptions.reactRoutes);
}
// initialize the markup string
var html = Config.docType;
// create the data object that will be fed into the React render method.
// Data is a mash of the express' `render options` and `res.locals`
// and meta info about `react-engine`
var data = merge({
__meta: {
// get just the relative path for view file name
view: null,
markupId: Config.client.markupId
}
}, omit(options, ['settings', 'enrouten', '_locals']));
if (this.useRouter && !routes) {
return done(new Error('asking to use react router for rendering, but no routes are provided'));
}
var componentInstance;
try {
if (this.useRouter) {
// runs the react router that gives the Component to render
Router.run(routes, thing, function onRouterRun(Component) {
componentInstance = React.createElement(Component, data);
});
}
else {
data.__meta.view = thing.replace(options.settings.views, '').substring(1);
var view = require(thing);
// create the Component using react's createFactory
var component = React.createFactory(view);
componentInstance = component(data);
}
// render the componentInstance
html += React.renderToString(componentInstance);
// state (script) injection
var script = format(TEMPLATE, Config.client.markupId, JSON.stringify(data));
html = html.replace('</head>', script + '</head>');
return done(null, html);
}
catch (err) {
// on error, pass to the next
// middleware in the chain!
return done(err);
}
};
};
| lib/server.js | /*-------------------------------------------------------------------------------------------------------------------*\
| Copyright (C) 2015 PayPal |
| |
| Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance |
| with the License. |
| |
| You may obtain a copy of the License at |
| |
| http://www.apache.org/licenses/LICENSE-2.0 |
| |
| Unless required by applicable law or agreed to in writing, software distributed under the License is distributed |
| on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for |
| the specific language governing permissions and limitations under the License. |
\*-------------------------------------------------------------------------------------------------------------------*/
'use strict';
var util = require('./util');
var Config = require('./config');
var format = require('util').format;
var omit = require('lodash-node/compat/object/omit');
var merge = require('lodash-node/compat/object/merge');
// safely require the peer-dependencies
var React = util.safeRequire('react');
var Router = util.safeRequire('react-router');
// a template of the `script` tag that gets
// injected into the server rendered pages.
var TEMPLATE = ['<script id="%s" type="application/javascript">var ',
Config.client.variableName,
' = %s;</script>'
].join('');
exports.create = function create(createOptions) {
createOptions = createOptions || {};
// the render implementation
return function render(thing, options, callback) {
var routes;
function done(err, html) {
if (options.settings.env === 'development') {
// remove all the files under the express's view folder from require cache.
// Helps in making changes to react views without restarting the server.
util.clearRequireCache(createOptions.reactRoutes);
util.clearRequireCacheInDir(options.settings.views, options.settings['view engine']);
}
callback(err, html);
}
if (createOptions.reactRoutes) {
routes = require(createOptions.reactRoutes);
}
// initialize the markup string
var html = Config.docType;
// create the data object that will be fed into the React render method.
// Data is a mash of the express' `render options` and `res.locals`
// and meta info about `react-engine`
var data = merge({
__meta: {
// get just the relative path for view file name
view: null,
markupId: Config.client.markupId
}
}, omit(options, ['settings', 'enrouten', '_locals']));
if (this.useRouter && !routes) {
return done(new Error('asking to use react router for rendering, but no routes are provided'));
}
var componentInstance;
try {
if (this.useRouter) {
// runs the react router that gives the Component to render
Router.run(routes, thing, function onRouterRun(Component) {
componentInstance = React.createElement(Component, data);
});
}
else {
data.__meta.view = thing.replace(options.settings.views, '').substring(1);
var view = require(thing);
// create the Component using react's createFactory
var component = React.createFactory(view);
componentInstance = component(data);
}
// render the componentInstance
html += React.renderToString(componentInstance);
// state injection
html += format(TEMPLATE, Config.client.markupId, JSON.stringify(data));
return done(null, html);
}
catch (err) {
// on error, pass to the next
// middleware in the chain!
return done(err);
}
};
};
| Refactored: script tag template. Added: logic that injects script into <head/>
| lib/server.js | Refactored: script tag template. Added: logic that injects script into <head/> | <ide><path>ib/server.js
<ide>
<ide> // a template of the `script` tag that gets
<ide> // injected into the server rendered pages.
<del>var TEMPLATE = ['<script id="%s" type="application/javascript">var ',
<del> Config.client.variableName,
<del> ' = %s;</script>'
<del> ].join('');
<add>var TEMPLATE = '<script id="%s" type="application/javascript">window._store = %s;</script>';
<ide>
<ide> exports.create = function create(createOptions) {
<ide>
<ide> // render the componentInstance
<ide> html += React.renderToString(componentInstance);
<ide>
<del> // state injection
<del> html += format(TEMPLATE, Config.client.markupId, JSON.stringify(data));
<add> // state (script) injection
<add> var script = format(TEMPLATE, Config.client.markupId, JSON.stringify(data));
<add> html = html.replace('</head>', script + '</head>');
<ide>
<ide> return done(null, html);
<ide> } |
|
JavaScript | agpl-3.0 | 14c2e566cbda5107f6336f45270783cedf98b32d | 0 | vladnicoara/SDLive-Blog,superdesk/Live-Blog,superdesk/Live-Blog,superdesk/Live-Blog,vladnicoara/SDLive-Blog,superdesk/Live-Blog,vladnicoara/SDLive-Blog | define('jquery/rest',['jquery', 'jquery/utils'], function ($) {
var dfdManager =
{
add: function(parentDfd, childDfd)
{
childDfd.children = [];
if(typeof parentDfd.children == 'undefined') parentDfd.children = [];
parentDfd.children.push(childDfd);
},
stop: function(dfd)
{
if(typeof dfd.children != 'undefined')
for(var i in dfd.children)
dfdManager.stop(dfd.children[i]);
dfd.reject();
}
};
function chainable(fn, name)
{
this.deferred = $.Deferred();
//this.deferred.progress(function(){ console.log('progress '+this.name+' with', arguments) })
this.fn = fn;
this.name = name;
};
chainable.prototype.promise = function()
{
return this.deferred.promise();
};
chainable.prototype.invoke = function()
{
this.fn.apply(this, arguments)
return this;
};
/*!
* Private method to get the url
*/
function getUrl()
{
if( (this.lastUrl.substr(0,4).toLowerCase() === 'http') ||
(this.lastUrl.substr(0,5).toLowerCase() === 'https') ||
(this.lastUrl.substr(0,2) === '//') ) {
return this.lastUrl;
} else if(this.lastUrl.substr(0,1) === '/' ) {
return this.config.apiUrl+this.lastUrl;
} else {
return this.config.apiUrl+this.config.resourcePath+this.lastUrl;
}
}
/*!
* construct
*/
function resource()
{
arguments.length && this._construct.apply(this, arguments);
};
resource.prototype =
{
_: '',
getData: [],
lastAdded: {},
lastUrl: '',
job: [],
initXFrom: false,
respArgs: null,
dataChanged: false,
initData: undefined,
fromData: undefined,
getData: [],
_construct: function()
{
var self = this,
extractListData = this.extractListData;
this.getData = [];
if( typeof arguments[0] == 'string' )
{
self.lastUrl = arguments[0];
self.request({url :
arguments[0].indexOf('http://') !== -1 ? arguments[0] :
self.config.apiUrl+self.config.resourcePath+arguments[0] });
var resolve = null;
self.initData = new chainable( function()
{
if( resolve && !self.dataChanged )
{
this.deferred.resolve(resolve);
return ret;
};
if( typeof this.request != 'undefined' ) self.request(this.request);
return self.doRequest()
.pipe(function(data)
{
resolve = extractListData(data);
self.dataChanged = false;
return resolve;
})
.then(this.deferred.resolve, this.deferred.reject);
}, 'initData from ajax');
}
else
{
var ret = extractListData(arguments[0]);
this.initData = new chainable(function()
{
this.deferred.resolve(ret); return ret;
}, 'initData with data');
}
this.lastAdded = this.initData;
this.fromData = new chainable(function(data){ this.deferred.resolve(data); }, 'fromInit');
var fromData = this.fromData,
self = this;
fromData.promise().always(function(){ self.initXFrom = false; })
self.initXFrom = true;
$.when(this.initData).then(function()
{
fromData.invoke.apply(fromData, arguments);
}, fromData.deferred.reject );
if(arguments[1]) this.name = arguments[1];
},
extractListData: function(data)
{
var ret = data;
if( !Array.isArray(data) ) for( i in data )
{
if( Array.isArray(data[i]) )
{
ret = data[i];
break;
}
}
return ret;
},
config:
{
resourcePath: '/resources/',
apiUrl: ''
},
requestOptions:
{
dataType: 'json',
type: 'get',
headers: { 'Accept' : 'text/json' }
},
chainable: chainable,
/*!
* get item from the already existing list
*/
from: function(key)
{
var self = this,
args = arguments;
this.fromData = new chainable( function(list)
{
var found = false;
for( var item in list )
{
if( typeof key != 'object' && item != key ) continue;
found = list[item];
// for each key check if exists and is the value
for( keyName in key )
if(!(keyName in list[item]) || list[item][keyName] != key[keyName])
{
found = false;
break;
}
if( found ) break;
}
if( !found || typeof found.href == 'undefined' ) return this.deferred.reject();
var fromUrl = found.href;
if( args.length > 1 )
{
if(typeof args[1] == 'function')
fromUrl = args[1](found); // filter function for complex structures
if(typeof args[1] == 'object')
self.request(args[1]);
if(typeof args[2] == 'object')
self.request(args[2]);
}
if( typeof this.request != 'undefined' )
self.request(this.request);
self.lastUrl = fromUrl;
return self
.doRequest(fromUrl)
.pipe(function(data)
{
self.fromData.fn = function()
{
this.deferred.resolve(data);
return data;
};
return data;
})
.then(this.deferred.resolve, this.deferred.reject);
}, "from "+key);
var fromData = this.fromData;
this.lastAdded = fromData;
if(!self.initXFrom)
{
self.iniXFrom = true;
$.when(this.initData).then(function(){ fromData.invoke.apply(fromData, arguments); }, fromData.deferred.reject );
}
if( typeof this.insideJob != 'undefined' )
this.insideJob.push(fromData);
return this;
},
/*!
* register an operation to obtain a key value from an object node
* obtained by the last operation either from or construct
*/
get: function(key)
{
var self = this;
var args = arguments;
var getData = new chainable( function(data)
{
var node;
if( !Array.isArray(data) && $.isObject(data) )
if( Object.keys(data).length == 1 )
{
for( var i in data )
if( key in data[i] )
node = data[i][key]
}
else if(typeof data[key] != 'undefined') node = data[key];
if(typeof node == 'undefined')
{
this.deferred.resolve(null);
return false;
}
// assume that we only have a href property provided and we need to follow it to get the entity
if(typeof node.href == 'string' && Object.keys(node).length == 1)
{
var dfd = this.deferred;
if(typeof args[1] != 'undefined' )
self.request(args[1]);
if( typeof this.request != 'undefined' )
self.request(this.request);
self.lastUrl = node.href;
var ajax = self.doRequest(node.href)
.then(this.deferred.resolve, this.deferred.reject);
return ajax;
}
// assume we have all/the filtered properties
else
return this.deferred.resolve(node);
}, "get "+key);
this.getData.push(getData);
this.lastAdded = getData;
$.when(this.fromData).then(function(){ getData.invoke.apply(getData, arguments); }, getData.deferred.reject );
if( typeof this.insideJob != 'undefined' )
this.insideJob.push(getData);
return this;
},
/*!
* execute operations and optionally execute a callback
*/
done: function()
{
if( !this.getData.length )
{
var getInit = new chainable(function(data)
{
this.deferred.resolve(data);
}, 'getInit');
getInit.isInit = true;
this.getData = [getInit];
$.when(this.fromData).then(function(){ getInit.invoke.apply(getInit, arguments); }, getInit.deferred.reject );
}
var self = this,
name = arguments[1];
if( typeof arguments[0] == 'function' )
{
var callback = arguments[0],
failCallback = $.noop;
if(typeof arguments[1] == 'function')
failCallback = arguments[1];
$.when.apply($, this.getData).then(function()
{
var args = $.makeArray(arguments);
if( typeof self.spawned != 'undefined' )
args = args.concat(self.spawned);
var result = callback.apply(self, args);
},
function()
{
failCallback.apply(self, arguments);
})
.always(function() // we need to reset at least initData for future chains..
{
self.initData = new chainable(self.initData.fn, 'reset');
self.fromData = new chainable(self.fromData.fn, 'reset');
self.initXFrom = true;
$.when(self.initData).then(function()
{
self.fromData.invoke.apply(self.fromData, arguments);
}, self.fromData.deferred.reject );
});
}
var trigger = $.Deferred();
trigger.resolve();
var initData = this.initData;
$.when(trigger).then(function(){ initData.invoke.apply( initData, arguments ); });
self.getData = [];
return this;
},
resetJob: function()
{
if(typeof this.job == 'undefined') return this;
for(var i in this.job)
this.job[i].deferred.reject();
this.job = [];
return this;
},
registerToJob: function(job)
{
this.insideJob = job;
return this;
},
/*!
* execute this callback regardless of fail or done get operations
*/
always: function(callback)
{
var self = this;
var dfd = $.Deferred();
$.when(dfd).then(function(data)
{
if(typeof callback == 'function')
callback.apply(self, data);
});
var progress = this.getData.length;
var args = [];
$(this.getData).each(function(i, fn)
{
fn.promise().always(function()
{
progress--;
if(arguments.length > 1) // if more than 1 argument put them in an array
args.splice(i, 0, arguments);
else // else just the single one
args.splice(i, 0, arguments[0]);
if(!progress)
dfd.resolve(args);
});
})
return this;
},
/*!
* spawn a new resource rom the last get method called
*/
spawn: function()
{
var self = this;
$.when(this.lastAdded).pipe(function(data)
{
self.spawned = new resource(data, 'spawned');
self.spawned.lastUrl = self.lastUrl;
// TODO add backreference or not?
return data;
});
return this;
},
/*!
* make the request
* @param string url
*/
doRequest: function()
{
if(typeof arguments[0] == 'string') this.request({url: arguments[0]});
var self = this,
ajax = $.ajax(this.requestOptions)
.fail(function(){ $(self).trigger('failed', arguments); })
.always(function(){ self.respArgs = arguments[0]; });
if(!this.keepXFilter)
delete this.requestOptions.headers['X-Filter'];
return ajax;
},
responseArgs: function()
{
return this.respArgs;
},
/*!
*
*/
update: function(data, url)
{
if( this.lastAdded.request )
$.extend(this.lastAdded.request.headers, {'X-HTTP-Method-Override': 'PUT'});
else
this.lastAdded.request = {headers: {'X-HTTP-Method-Override': 'PUT'}};
this.request({type: 'post', headers: this.lastAdded.request.headers, data: data});
return this.doRequest(url ? url : getUrl.apply(this));
},
/*!
*
*/
insert: function(data, url)
{
this.request({type: 'post', data: data, headers: this.lastAdded.request ? this.lastAdded.request.headers : {}});
return this.doRequest(url ? url : getUrl.apply(this));
},
/*!
*
*/
delete: function(data, url)
{
if( this.lastAdded.request )
$.extend(this.lastAdded.request.headers, {'X-HTTP-Method-Override': 'DELETE'});
else
this.lastAdded.request = {headers: {'X-HTTP-Method-Override': 'DELETE'}};
this.request({type: 'post', headers: this.lastAdded.request.headers, data: data});
return this.doRequest(url ? url : getUrl.apply(this));
},
/*!
* extend request options
*/
request: function(options)
{
if( options.hasOwnProperty('data') ) this.dataChanged = true;
this.requestOptions = $.extend(true, {}, this.requestOptions, options);
return this;
},
/*!
* reset request option data, optionally by key
*/
resetData: function(key)
{
if( !this.requestOptions.data ) return this;
if( typeof key == 'undefined' ) {
delete this.requestOptions.data;
return this;
}
delete this.requestOptions.data[key];
return this;
},
/*!
*
*/
xfilter: function(value)
{
this.lastAdded.request = { headers: { 'X-Filter' : value } };
return this;
}
};
$.extend($, {rest : resource});
function restAuth()
{
resource.apply(this, arguments);
}
restAuth.prototype = Object.create(new resource(),
{
_construct: { value: function()
{
this.config = $.extend({}, this.config, {resourcePath: '/resources/my/'});
//this.requestOptions.headers.Authorization = 111;
resource.prototype._construct.apply(this, arguments);
}, enumerable: true, configurable: true, writable: true }
});
$.extend($, {restAuth : restAuth});
}); | plugins/gui-core/gui-resources/scripts/js/jquery/rest.js | define('jquery/rest',['jquery', 'jquery/utils'], function ($) {
var dfdManager =
{
add: function(parentDfd, childDfd)
{
childDfd.children = [];
if(typeof parentDfd.children == 'undefined') parentDfd.children = [];
parentDfd.children.push(childDfd);
},
stop: function(dfd)
{
if(typeof dfd.children != 'undefined')
for(var i in dfd.children)
dfdManager.stop(dfd.children[i]);
dfd.reject();
}
};
function chainable(fn, name)
{
this.deferred = $.Deferred();
//this.deferred.progress(function(){ console.log('progress '+this.name+' with', arguments) })
this.fn = fn;
this.name = name;
};
chainable.prototype.promise = function()
{
return this.deferred.promise();
};
chainable.prototype.invoke = function()
{
this.fn.apply(this, arguments)
return this;
};
/*!
* Private method to get the url
*/
function getUrl()
{
if( (this.lastUrl.substr(0,4).toLowerCase() === 'http') ||
(this.lastUrl.substr(0,5).toLowerCase() === 'https') ||
(this.lastUrl.substr(0,2) === '//') ) {
return this.lastUrl;
} else if(this.lastUrl.substr(0,1) === '/' ) {
return this.config.apiUrl+this.lastUrl;
} else {
return this.config.apiUrl+this.config.resourcePath+this.lastUrl;
}
}
/*!
* construct
*/
function resource()
{
arguments.length && this._construct.apply(this, arguments);
};
resource.prototype =
{
_: '',
getData: [],
lastAdded: {},
lastUrl: '',
job: [],
initXFrom: false,
respArgs: null,
dataChanged: false,
initData: undefined,
fromData: undefined,
getData: [],
_construct: function()
{
var self = this,
extractListData = this.extractListData;
this.getData = [];
if( typeof arguments[0] == 'string' )
{
self.lastUrl = arguments[0];
self.request({url :
arguments[0].indexOf('http://') !== -1 ? arguments[0] :
self.config.apiUrl+self.config.resourcePath+arguments[0] });
var resolve = null;
self.initData = new chainable( function()
{
if( resolve && !self.dataChanged )
{
this.deferred.resolve(resolve);
return ret;
};
if( typeof this.request != 'undefined' ) self.request(this.request);
return self.doRequest()
.pipe(function(data)
{
resolve = extractListData(data);
self.dataChanged = false;
return resolve;
})
.then(this.deferred.resolve, this.deferred.reject);
}, 'initData from ajax');
}
else
{
var ret = extractListData(arguments[0]);
this.initData = new chainable(function()
{
this.deferred.resolve(ret); return ret;
}, 'initData with data');
}
this.lastAdded = this.initData;
this.fromData = new chainable(function(data){ this.deferred.resolve(data); }, 'fromInit');
var fromData = this.fromData,
self = this;
fromData.promise().always(function(){ self.initXFrom = false; })
self.initXFrom = true;
$.when(this.initData).then(function()
{
fromData.invoke.apply(fromData, arguments);
}, fromData.deferred.reject );
if(arguments[1]) this.name = arguments[1];
},
extractListData: function(data)
{
var ret = data;
if( !Array.isArray(data) ) for( i in data )
{
if( Array.isArray(data[i]) )
{
ret = data[i];
break;
}
}
return ret;
},
config:
{
resourcePath: '/resources/',
apiUrl: ''
},
requestOptions:
{
dataType: 'json',
type: 'get',
headers: { 'Accept' : 'text/json' }
},
chainable: chainable,
/*!
* get item from the already existing list
*/
from: function(key)
{
var self = this,
args = arguments;
this.fromData = new chainable( function(list)
{
var found = false;
for( var item in list )
{
if( typeof key != 'object' && item != key ) continue;
found = list[item];
// for each key check if exists and is the value
for( keyName in key )
if(!(keyName in list[item]) || list[item][keyName] != key[keyName])
{
found = false;
break;
}
if( found ) break;
}
if( !found || typeof found.href == 'undefined' ) return this.deferred.reject();
var fromUrl = found.href;
if( args.length > 1 )
{
if(typeof args[1] == 'function')
fromUrl = args[1](found); // filter function for complex structures
if(typeof args[1] == 'object')
self.request(args[1]);
if(typeof args[2] == 'object')
self.request(args[2]);
}
if( typeof this.request != 'undefined' )
self.request(this.request);
self.lastUrl = fromUrl;
return self
.doRequest(fromUrl)
.pipe(function(data)
{
self.fromData.fn = function()
{
this.deferred.resolve(data);
return data;
};
return data;
})
.then(this.deferred.resolve, this.deferred.reject);
}, "from "+key);
var fromData = this.fromData;
this.lastAdded = fromData;
if(!self.initXFrom)
{
self.iniXFrom = true;
$.when(this.initData).then(function(){ fromData.invoke.apply(fromData, arguments); }, fromData.deferred.reject );
}
if( typeof this.insideJob != 'undefined' )
this.insideJob.push(fromData);
return this;
},
/*!
* register an operation to obtain a key value from an object node
* obtained by the last operation either from or construct
*/
get: function(key)
{
var self = this;
var args = arguments;
var getData = new chainable( function(data)
{
var node;
if( !Array.isArray(data) && $.isObject(data) )
if( Object.keys(data).length == 1 )
{
for( var i in data )
if( key in data[i] )
node = data[i][key]
}
else if(typeof data[key] != 'undefined') node = data[key];
if(typeof node == 'undefined')
{
this.deferred.resolve(null);
return false;
}
// assume that we only have a href property provided and we need to follow it to get the entity
if(typeof node.href == 'string' && Object.keys(node).length == 1)
{
var dfd = this.deferred;
if(typeof args[1] != 'undefined' )
self.request(args[1]);
if( typeof this.request != 'undefined' )
self.request(this.request);
self.lastUrl = node.href;
var ajax = self.doRequest(node.href)
.then(this.deferred.resolve, this.deferred.reject);
return ajax;
}
// assume we have all/the filtered properties
else
return this.deferred.resolve(node);
}, "get "+key);
this.getData.push(getData);
this.lastAdded = getData;
$.when(this.fromData).then(function(){ getData.invoke.apply(getData, arguments); }, getData.deferred.reject );
if( typeof this.insideJob != 'undefined' )
this.insideJob.push(getData);
return this;
},
/*!
* execute operations and optionally execute a callback
*/
done: function()
{
if( !this.getData.length )
{
var getInit = new chainable(function(data)
{
this.deferred.resolve(data);
}, 'getInit');
getInit.isInit = true;
this.getData = [getInit];
$.when(this.fromData).then(function(){ getInit.invoke.apply(getInit, arguments); }, getInit.deferred.reject );
}
var self = this,
name = arguments[1];
if( typeof arguments[0] == 'function' )
{
var callback = arguments[0],
failCallback = $.noop;
if(typeof arguments[1] == 'function')
failCallback = arguments[1];
$.when.apply($, this.getData).then(function()
{
var args = $.makeArray(arguments);
if( typeof self.spawned != 'undefined' )
args = args.concat(self.spawned);
var result = callback.apply(self, args);
},
function()
{
failCallback.apply(self, arguments);
})
.always(function() // we need to reset at least initData for future chains..
{
self.initData = new chainable(self.initData.fn, 'reset');
self.fromData = new chainable(self.fromData.fn, 'reset');
self.initXFrom = true;
$.when(self.initData).then(function()
{
self.fromData.invoke.apply(self.fromData, arguments);
}, self.fromData.deferred.reject );
});
}
var trigger = $.Deferred();
trigger.resolve();
var initData = this.initData;
$.when(trigger).then(function(){ initData.invoke.apply( initData, arguments ); });
self.getData = [];
return this;
},
resetJob: function()
{
if(typeof this.job == 'undefined') return this;
for(var i in this.job)
this.job[i].deferred.reject();
this.job = [];
return this;
},
registerToJob: function(job)
{
this.insideJob = job;
return this;
},
/*!
* execute this callback regardless of fail or done get operations
*/
always: function(callback)
{
var self = this;
var dfd = $.Deferred();
$.when(dfd).then(function(data)
{
if(typeof callback == 'function')
callback.apply(self, data);
});
var progress = this.getData.length;
var args = [];
$(this.getData).each(function(i, fn)
{
fn.promise().always(function()
{
progress--;
if(arguments.length > 1) // if more than 1 argument put them in an array
args.splice(i, 0, arguments);
else // else just the single one
args.splice(i, 0, arguments[0]);
if(!progress)
dfd.resolve(args);
});
})
return this;
},
/*!
* spawn a new resource rom the last get method called
*/
spawn: function()
{
var self = this;
$.when(this.lastAdded).pipe(function(data)
{
self.spawned = new resource(data, 'spawned');
self.spawned.lastUrl = self.lastUrl;
// TODO add backreference or not?
return data;
});
return this;
},
/*!
* make the request
* @param string url
*/
doRequest: function()
{
if(typeof arguments[0] == 'string') this.request({url: arguments[0]});
var self = this,
ajax = $.ajax(this.requestOptions)
.fail(function(){ $(self).trigger('failed', arguments); })
.always(function(){ self.respArgs = arguments[0]; });
if(!this.keepXFilter)
delete this.requestOptions.headers['X-Filter'];
return ajax;
},
responseArgs: function()
{
return this.respArgs;
},
/*!
*
*/
update: function(data, url)
{
this.lastAdded.request && $.extend(this.lastAdded.request.headers, {'X-HTTP-Method-Override': 'PUT'});
this.request({type: 'post', headers: this.lastAdded.request.headers, data: data});
return this.doRequest(url ? url : getUrl.apply(this));
},
/*!
*
*/
insert: function(data, url)
{
this.request({type: 'post', data: data, headers: this.lastAdded.request ? this.lastAdded.request.headers : {}});
return this.doRequest(url ? url : getUrl.apply(this));
},
/*!
*
*/
delete: function(data, url)
{
this.lastAdded.request && $.extend(this.lastAdded.request.headers, {'X-HTTP-Method-Override': 'DELETE'});
this.request({type: 'post', headers: this.lastAdded.request.headers, data: data});
return this.doRequest(url ? url : getUrl.apply(this));
},
/*!
* extend request options
*/
request: function(options)
{
if( options.hasOwnProperty('data') ) this.dataChanged = true;
this.requestOptions = $.extend(true, {}, this.requestOptions, options);
return this;
},
/*!
* reset request option data, optionally by key
*/
resetData: function(key)
{
if( !this.requestOptions.data ) return this;
if( typeof key == 'undefined' ) {
delete this.requestOptions.data;
return this;
}
delete this.requestOptions.data[key];
return this;
},
/*!
*
*/
xfilter: function(value)
{
this.lastAdded.request = { headers: { 'X-Filter' : value } };
return this;
}
};
$.extend($, {rest : resource});
function restAuth()
{
resource.apply(this, arguments);
}
restAuth.prototype = Object.create(new resource(),
{
_construct: { value: function()
{
this.config = $.extend({}, this.config, {resourcePath: '/resources/my/'});
//this.requestOptions.headers.Authorization = 111;
resource.prototype._construct.apply(this, arguments);
}, enumerable: true, configurable: true, writable: true }
});
$.extend($, {restAuth : restAuth});
}); | NR-151 : Necessary core features features and fixes
...
| plugins/gui-core/gui-resources/scripts/js/jquery/rest.js | NR-151 : Necessary core features features and fixes | <ide><path>lugins/gui-core/gui-resources/scripts/js/jquery/rest.js
<ide> */
<ide> update: function(data, url)
<ide> {
<del> this.lastAdded.request && $.extend(this.lastAdded.request.headers, {'X-HTTP-Method-Override': 'PUT'});
<add> if( this.lastAdded.request )
<add> $.extend(this.lastAdded.request.headers, {'X-HTTP-Method-Override': 'PUT'});
<add> else
<add> this.lastAdded.request = {headers: {'X-HTTP-Method-Override': 'PUT'}};
<ide> this.request({type: 'post', headers: this.lastAdded.request.headers, data: data});
<ide> return this.doRequest(url ? url : getUrl.apply(this));
<ide> },
<ide> */
<ide> delete: function(data, url)
<ide> {
<del> this.lastAdded.request && $.extend(this.lastAdded.request.headers, {'X-HTTP-Method-Override': 'DELETE'});
<add> if( this.lastAdded.request )
<add> $.extend(this.lastAdded.request.headers, {'X-HTTP-Method-Override': 'DELETE'});
<add> else
<add> this.lastAdded.request = {headers: {'X-HTTP-Method-Override': 'DELETE'}};
<ide> this.request({type: 'post', headers: this.lastAdded.request.headers, data: data});
<ide> return this.doRequest(url ? url : getUrl.apply(this));
<ide> }, |
|
Java | apache-2.0 | e31e91772f0babbfd951403b51bb6d88c797e2e8 | 0 | mahak/hbase,lshmouse/hbase,Guavus/hbase,mapr/hbase,joshelser/hbase,Eshcar/hbase,HubSpot/hbase,SeekerResource/hbase,justintung/hbase,andrewmains12/hbase,gustavoanatoly/hbase,bijugs/hbase,joshelser/hbase,HubSpot/hbase,ultratendency/hbase,amyvmiwei/hbase,mapr/hbase,narendragoyal/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,SeekerResource/hbase,ChinmaySKulkarni/hbase,juwi/hbase,drewpope/hbase,bijugs/hbase,JingchengDu/hbase,joshelser/hbase,toshimasa-nasu/hbase,SeekerResource/hbase,HubSpot/hbase,ultratendency/hbase,HubSpot/hbase,StackVista/hbase,gustavoanatoly/hbase,Eshcar/hbase,narendragoyal/hbase,SeekerResource/hbase,ibmsoe/hbase,Apache9/hbase,gustavoanatoly/hbase,amyvmiwei/hbase,gustavoanatoly/hbase,justintung/hbase,HubSpot/hbase,apurtell/hbase,amyvmiwei/hbase,ndimiduk/hbase,andrewmains12/hbase,Eshcar/hbase,ndimiduk/hbase,drewpope/hbase,ndimiduk/hbase,bijugs/hbase,mahak/hbase,Guavus/hbase,ndimiduk/hbase,ibmsoe/hbase,gustavoanatoly/hbase,SeekerResource/hbase,vincentpoon/hbase,juwi/hbase,vincentpoon/hbase,apurtell/hbase,amyvmiwei/hbase,drewpope/hbase,lshmouse/hbase,JingchengDu/hbase,francisliu/hbase,intel-hadoop/hbase-rhino,StackVista/hbase,justintung/hbase,andrewmains12/hbase,gustavoanatoly/hbase,Apache9/hbase,Apache9/hbase,Apache9/hbase,mahak/hbase,ultratendency/hbase,juwi/hbase,toshimasa-nasu/hbase,ultratendency/hbase,justintung/hbase,joshelser/hbase,bijugs/hbase,ultratendency/hbase,ndimiduk/hbase,Apache9/hbase,Eshcar/hbase,ChinmaySKulkarni/hbase,lshmouse/hbase,drewpope/hbase,lshmouse/hbase,juwi/hbase,andrewmains12/hbase,drewpope/hbase,intel-hadoop/hbase-rhino,bijugs/hbase,JingchengDu/hbase,bijugs/hbase,Apache9/hbase,bijugs/hbase,ChinmaySKulkarni/hbase,HubSpot/hbase,apurtell/hbase,andrewmains12/hbase,JingchengDu/hbase,lshmouse/hbase,andrewmains12/hbase,justintung/hbase,narendragoyal/hbase,lshmouse/hbase,bijugs/hbase,Eshcar/hbase,joshelser/hbase,ibmsoe/hbase,ndimiduk/hbase,joshelser/hbase,toshimasa-nasu/hbase,gustavoanatoly/hbase,francisliu/hbase,StackVista/hbase,mapr/hbase,gustavoanatoly/hbase,vincentpoon/hbase,francisliu/hbase,SeekerResource/hbase,ChinmaySKulkarni/hbase,ibmsoe/hbase,ndimiduk/hbase,mahak/hbase,vincentpoon/hbase,JingchengDu/hbase,andrewmains12/hbase,vincentpoon/hbase,mapr/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,JingchengDu/hbase,ChinmaySKulkarni/hbase,narendragoyal/hbase,Apache9/hbase,vincentpoon/hbase,Eshcar/hbase,Apache9/hbase,amyvmiwei/hbase,juwi/hbase,justintung/hbase,ibmsoe/hbase,Eshcar/hbase,mapr/hbase,toshimasa-nasu/hbase,francisliu/hbase,SeekerResource/hbase,mahak/hbase,ChinmaySKulkarni/hbase,ultratendency/hbase,Guavus/hbase,apurtell/hbase,ultratendency/hbase,ibmsoe/hbase,justintung/hbase,juwi/hbase,narendragoyal/hbase,gustavoanatoly/hbase,StackVista/hbase,Guavus/hbase,justintung/hbase,StackVista/hbase,toshimasa-nasu/hbase,drewpope/hbase,StackVista/hbase,StackVista/hbase,ibmsoe/hbase,ultratendency/hbase,francisliu/hbase,narendragoyal/hbase,apurtell/hbase,toshimasa-nasu/hbase,vincentpoon/hbase,ChinmaySKulkarni/hbase,ultratendency/hbase,justintung/hbase,JingchengDu/hbase,SeekerResource/hbase,ndimiduk/hbase,Eshcar/hbase,intel-hadoop/hbase-rhino,francisliu/hbase,mahak/hbase,apurtell/hbase,mapr/hbase,mahak/hbase,amyvmiwei/hbase,joshelser/hbase,ibmsoe/hbase,narendragoyal/hbase,Guavus/hbase,joshelser/hbase,ibmsoe/hbase,lshmouse/hbase,intel-hadoop/hbase-rhino,lshmouse/hbase,intel-hadoop/hbase-rhino,francisliu/hbase,StackVista/hbase,francisliu/hbase,amyvmiwei/hbase,intel-hadoop/hbase-rhino,gustavoanatoly/hbase,HubSpot/hbase,ultratendency/hbase,Apache9/hbase,amyvmiwei/hbase,justintung/hbase,mahak/hbase,JingchengDu/hbase,toshimasa-nasu/hbase,joshelser/hbase,ChinmaySKulkarni/hbase,StackVista/hbase,mapr/hbase,HubSpot/hbase,intel-hadoop/hbase-rhino,Guavus/hbase,amyvmiwei/hbase,narendragoyal/hbase,ndimiduk/hbase,toshimasa-nasu/hbase,Guavus/hbase,apurtell/hbase,SeekerResource/hbase,amyvmiwei/hbase,Guavus/hbase,intel-hadoop/hbase-rhino,drewpope/hbase,vincentpoon/hbase,JingchengDu/hbase,juwi/hbase,SeekerResource/hbase,apurtell/hbase,juwi/hbase,mahak/hbase,HubSpot/hbase,narendragoyal/hbase,francisliu/hbase,Eshcar/hbase,ibmsoe/hbase,juwi/hbase,intel-hadoop/hbase-rhino,drewpope/hbase,ndimiduk/hbase,Apache9/hbase,lshmouse/hbase,JingchengDu/hbase,Eshcar/hbase,vincentpoon/hbase,bijugs/hbase,narendragoyal/hbase,drewpope/hbase,StackVista/hbase,mapr/hbase,joshelser/hbase,lshmouse/hbase,bijugs/hbase,toshimasa-nasu/hbase,apurtell/hbase,HubSpot/hbase,Guavus/hbase,mapr/hbase,Guavus/hbase,andrewmains12/hbase,apurtell/hbase,intel-hadoop/hbase-rhino,vincentpoon/hbase,francisliu/hbase,mahak/hbase | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.replication;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.ClusterId;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Category;
/**
* This class tests the ReplicationTrackerZKImpl class and ReplicationListener interface. One
* MiniZKCluster is used throughout the entire class. The cluster is initialized with the creation
* of the rsZNode. All other znode creation/initialization is handled by the replication state
* interfaces (i.e. ReplicationPeers, etc.). Each test case in this class should ensure that the
* MiniZKCluster is cleaned and returned to it's initial state (i.e. nothing but the rsZNode).
*/
@Category(MediumTests.class)
public class TestReplicationTrackerZKImpl {
private static final Log LOG = LogFactory.getLog(TestReplicationTrackerZKImpl.class);
private static Configuration conf;
private static HBaseTestingUtility utility;
// Each one of the below variables are reinitialized before every test case
private ZooKeeperWatcher zkw;
private ReplicationPeers rp;
private ReplicationTracker rt;
private AtomicInteger rsRemovedCount;
private String rsRemovedData;
private AtomicInteger plChangedCount;
private List<String> plChangedData;
private AtomicInteger peerRemovedCount;
private String peerRemovedData;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
utility = new HBaseTestingUtility();
utility.startMiniZKCluster();
conf = utility.getConfiguration();
ZooKeeperWatcher zk = HBaseTestingUtility.getZooKeeperWatcher(utility);
ZKUtil.createWithParents(zk, zk.rsZNode);
}
@Before
public void setUp() throws Exception {
zkw = HBaseTestingUtility.getZooKeeperWatcher(utility);
String fakeRs1 = ZKUtil.joinZNode(zkw.rsZNode, "hostname1.example.org:1234");
try {
ZKClusterId.setClusterId(zkw, new ClusterId());
rp = ReplicationFactory.getReplicationPeers(zkw, conf, zkw);
rp.init();
rt = ReplicationFactory.getReplicationTracker(zkw, rp, conf, zkw, new DummyServer(fakeRs1));
} catch (Exception e) {
fail("Exception during test setup: " + e);
}
rsRemovedCount = new AtomicInteger(0);
rsRemovedData = "";
plChangedCount = new AtomicInteger(0);
plChangedData = new ArrayList<String>();
peerRemovedCount = new AtomicInteger(0);
peerRemovedData = "";
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
utility.shutdownMiniZKCluster();
}
@Test
public void testGetListOfRegionServers() throws Exception {
// 0 region servers
assertEquals(0, rt.getListOfRegionServers().size());
// 1 region server
ZKUtil.createWithParents(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname1.example.org:1234"));
assertEquals(1, rt.getListOfRegionServers().size());
// 2 region servers
ZKUtil.createWithParents(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname2.example.org:1234"));
assertEquals(2, rt.getListOfRegionServers().size());
// 1 region server
ZKUtil.deleteNode(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname2.example.org:1234"));
assertEquals(1, rt.getListOfRegionServers().size());
// 0 region server
ZKUtil.deleteNode(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname1.example.org:1234"));
assertEquals(0, rt.getListOfRegionServers().size());
}
@Test(timeout = 30000)
public void testRegionServerRemovedEvent() throws Exception {
ZKUtil.createAndWatch(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname2.example.org:1234"),
HConstants.EMPTY_BYTE_ARRAY);
rt.registerListener(new DummyReplicationListener());
// delete one
ZKUtil.deleteNode(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname2.example.org:1234"));
// wait for event
while (rsRemovedCount.get() < 1) {
Thread.sleep(5);
}
assertEquals("hostname2.example.org:1234", rsRemovedData);
}
@Ignore ("Flakey") @Test(timeout = 30000)
public void testPeerRemovedEvent() throws Exception {
rp.addPeer("5", utility.getClusterKey());
rt.registerListener(new DummyReplicationListener());
rp.removePeer("5");
// wait for event
while (peerRemovedCount.get() < 1) {
Thread.sleep(5);
}
assertEquals("5", peerRemovedData);
}
@Ignore ("Flakey") @Test(timeout = 30000)
public void testPeerListChangedEvent() throws Exception {
// add a peer
rp.addPeer("5", utility.getClusterKey());
zkw.getRecoverableZooKeeper().getZooKeeper().getChildren("/hbase/replication/peers/5", true);
rt.registerListener(new DummyReplicationListener());
rp.disablePeer("5");
ZKUtil.deleteNode(zkw, "/hbase/replication/peers/5/peer-state");
// wait for event
int tmp = plChangedCount.get();
while (plChangedCount.get() <= tmp) {
Thread.sleep(5);
}
assertEquals(1, plChangedData.size());
assertTrue(plChangedData.contains("5"));
// clean up
ZKUtil.deleteNode(zkw, "/hbase/replication/peers/5");
}
private class DummyReplicationListener implements ReplicationListener {
@Override
public void regionServerRemoved(String regionServer) {
rsRemovedData = regionServer;
rsRemovedCount.getAndIncrement();
LOG.debug("Received regionServerRemoved event: " + regionServer);
}
@Override
public void peerRemoved(String peerId) {
peerRemovedData = peerId;
peerRemovedCount.getAndIncrement();
LOG.debug("Received peerRemoved event: " + peerId);
}
@Override
public void peerListChanged(List<String> peerIds) {
plChangedData.clear();
plChangedData.addAll(peerIds);
plChangedCount.getAndIncrement();
LOG.debug("Received peerListChanged event");
}
}
private class DummyServer implements Server {
private String serverName;
private boolean isAborted = false;
private boolean isStopped = false;
public DummyServer(String serverName) {
this.serverName = serverName;
}
@Override
public Configuration getConfiguration() {
return conf;
}
@Override
public ZooKeeperWatcher getZooKeeper() {
return zkw;
}
@Override
public CatalogTracker getCatalogTracker() {
return null;
}
@Override
public ServerName getServerName() {
return new ServerName(this.serverName);
}
@Override
public void abort(String why, Throwable e) {
LOG.info("Aborting " + serverName);
this.isAborted = true;
}
@Override
public boolean isAborted() {
return this.isAborted;
}
@Override
public void stop(String why) {
this.isStopped = true;
}
@Override
public boolean isStopped() {
return this.isStopped;
}
}
}
| hbase-server/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationTrackerZKImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.replication;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.ClusterId;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.junit.AfterClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Category;
/**
* This class tests the ReplicationTrackerZKImpl class and ReplicationListener interface. One
* MiniZKCluster is used throughout the entire class. The cluster is initialized with the creation
* of the rsZNode. All other znode creation/initialization is handled by the replication state
* interfaces (i.e. ReplicationPeers, etc.). Each test case in this class should ensure that the
* MiniZKCluster is cleaned and returned to it's initial state (i.e. nothing but the rsZNode).
*/
@Category(MediumTests.class)
public class TestReplicationTrackerZKImpl {
private static final Log LOG = LogFactory.getLog(TestReplicationTrackerZKImpl.class);
private static Configuration conf;
private static HBaseTestingUtility utility;
// Each one of the below variables are reinitialized before every test case
private ZooKeeperWatcher zkw;
private ReplicationPeers rp;
private ReplicationTracker rt;
private AtomicInteger rsRemovedCount;
private String rsRemovedData;
private AtomicInteger plChangedCount;
private List<String> plChangedData;
private AtomicInteger peerRemovedCount;
private String peerRemovedData;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
utility = new HBaseTestingUtility();
utility.startMiniZKCluster();
conf = utility.getConfiguration();
ZooKeeperWatcher zk = HBaseTestingUtility.getZooKeeperWatcher(utility);
ZKUtil.createWithParents(zk, zk.rsZNode);
}
@Before
public void setUp() throws Exception {
zkw = HBaseTestingUtility.getZooKeeperWatcher(utility);
String fakeRs1 = ZKUtil.joinZNode(zkw.rsZNode, "hostname1.example.org:1234");
try {
ZKClusterId.setClusterId(zkw, new ClusterId());
rp = ReplicationFactory.getReplicationPeers(zkw, conf, zkw);
rp.init();
rt = ReplicationFactory.getReplicationTracker(zkw, rp, conf, zkw, new DummyServer(fakeRs1));
} catch (Exception e) {
fail("Exception during test setup: " + e);
}
rsRemovedCount = new AtomicInteger(0);
rsRemovedData = "";
plChangedCount = new AtomicInteger(0);
plChangedData = new ArrayList<String>();
peerRemovedCount = new AtomicInteger(0);
peerRemovedData = "";
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
utility.shutdownMiniZKCluster();
}
@Test
public void testGetListOfRegionServers() throws Exception {
// 0 region servers
assertEquals(0, rt.getListOfRegionServers().size());
// 1 region server
ZKUtil.createWithParents(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname1.example.org:1234"));
assertEquals(1, rt.getListOfRegionServers().size());
// 2 region servers
ZKUtil.createWithParents(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname2.example.org:1234"));
assertEquals(2, rt.getListOfRegionServers().size());
// 1 region server
ZKUtil.deleteNode(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname2.example.org:1234"));
assertEquals(1, rt.getListOfRegionServers().size());
// 0 region server
ZKUtil.deleteNode(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname1.example.org:1234"));
assertEquals(0, rt.getListOfRegionServers().size());
}
@Test(timeout = 30000)
public void testRegionServerRemovedEvent() throws Exception {
ZKUtil.createAndWatch(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname2.example.org:1234"),
HConstants.EMPTY_BYTE_ARRAY);
rt.registerListener(new DummyReplicationListener());
// delete one
ZKUtil.deleteNode(zkw, ZKUtil.joinZNode(zkw.rsZNode, "hostname2.example.org:1234"));
// wait for event
while (rsRemovedCount.get() < 1) {
Thread.sleep(5);
}
assertEquals("hostname2.example.org:1234", rsRemovedData);
}
@Test(timeout = 30000)
public void testPeerRemovedEvent() throws Exception {
rp.addPeer("5", utility.getClusterKey());
rt.registerListener(new DummyReplicationListener());
rp.removePeer("5");
// wait for event
while (peerRemovedCount.get() < 1) {
Thread.sleep(5);
}
assertEquals("5", peerRemovedData);
}
@Test(timeout = 30000)
public void testPeerListChangedEvent() throws Exception {
// add a peer
rp.addPeer("5", utility.getClusterKey());
zkw.getRecoverableZooKeeper().getZooKeeper().getChildren("/hbase/replication/peers/5", true);
rt.registerListener(new DummyReplicationListener());
rp.disablePeer("5");
ZKUtil.deleteNode(zkw, "/hbase/replication/peers/5/peer-state");
// wait for event
int tmp = plChangedCount.get();
while (plChangedCount.get() <= tmp) {
Thread.sleep(5);
}
assertEquals(1, plChangedData.size());
assertTrue(plChangedData.contains("5"));
// clean up
ZKUtil.deleteNode(zkw, "/hbase/replication/peers/5");
}
private class DummyReplicationListener implements ReplicationListener {
@Override
public void regionServerRemoved(String regionServer) {
rsRemovedData = regionServer;
rsRemovedCount.getAndIncrement();
LOG.debug("Received regionServerRemoved event: " + regionServer);
}
@Override
public void peerRemoved(String peerId) {
peerRemovedData = peerId;
peerRemovedCount.getAndIncrement();
LOG.debug("Received peerRemoved event: " + peerId);
}
@Override
public void peerListChanged(List<String> peerIds) {
plChangedData.clear();
plChangedData.addAll(peerIds);
plChangedCount.getAndIncrement();
LOG.debug("Received peerListChanged event");
}
}
private class DummyServer implements Server {
private String serverName;
private boolean isAborted = false;
private boolean isStopped = false;
public DummyServer(String serverName) {
this.serverName = serverName;
}
@Override
public Configuration getConfiguration() {
return conf;
}
@Override
public ZooKeeperWatcher getZooKeeper() {
return zkw;
}
@Override
public CatalogTracker getCatalogTracker() {
return null;
}
@Override
public ServerName getServerName() {
return new ServerName(this.serverName);
}
@Override
public void abort(String why, Throwable e) {
LOG.info("Aborting " + serverName);
this.isAborted = true;
}
@Override
public boolean isAborted() {
return this.isAborted;
}
@Override
public void stop(String why) {
this.isStopped = true;
}
@Override
public boolean isStopped() {
return this.isStopped;
}
}
}
| HBASE-9067 Temporarily disable a few tests in TestReplicationTrackerZKImpl
git-svn-id: 949c06ec81f1cb709fd2be51dd530a930344d7b3@1507764 13f79535-47bb-0310-9956-ffa450edef68
| hbase-server/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationTrackerZKImpl.java | HBASE-9067 Temporarily disable a few tests in TestReplicationTrackerZKImpl | <ide><path>base-server/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationTrackerZKImpl.java
<ide> import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
<ide> import org.junit.AfterClass;
<ide> import org.junit.Test;
<add>import org.junit.Ignore;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<ide> assertEquals("hostname2.example.org:1234", rsRemovedData);
<ide> }
<ide>
<del> @Test(timeout = 30000)
<add> @Ignore ("Flakey") @Test(timeout = 30000)
<ide> public void testPeerRemovedEvent() throws Exception {
<ide> rp.addPeer("5", utility.getClusterKey());
<ide> rt.registerListener(new DummyReplicationListener());
<ide> assertEquals("5", peerRemovedData);
<ide> }
<ide>
<del> @Test(timeout = 30000)
<add> @Ignore ("Flakey") @Test(timeout = 30000)
<ide> public void testPeerListChangedEvent() throws Exception {
<ide> // add a peer
<ide> rp.addPeer("5", utility.getClusterKey()); |
|
Java | agpl-3.0 | 88ea215f66848bedec4cbda26455d295a72834d2 | 0 | jotomo/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,MilosKozak/AndroidAPS,PoweRGbg/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,MilosKozak/AndroidAPS | package info.nightscout.androidaps.plugins.Wear.wearintegration;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
import org.mozilla.javascript.tools.jsc.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.Wear.WearPlugin;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
public class WatchUpdaterService extends WearableListenerService implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
public static final String ACTION_RESEND = WatchUpdaterService.class.getName().concat(".Resend");
public static final String ACTION_OPEN_SETTINGS = WatchUpdaterService.class.getName().concat(".OpenSettings");
public static final String ACTION_SEND_STATUS = WatchUpdaterService.class.getName().concat(".SendStatus");
public static final String ACTION_SEND_BASALS = WatchUpdaterService.class.getName().concat(".SendBasals");
public static final String ACTION_SEND_BOLUSPROGRESS = WatchUpdaterService.class.getName().concat(".BolusProgress");
public static final String ACTION_SEND_ACTIONCONFIRMATIONREQUEST = WatchUpdaterService.class.getName().concat(".ActionConfirmationRequest");
private GoogleApiClient googleApiClient;
public static final String WEARABLE_DATA_PATH = "/nightscout_watch_data";
public static final String WEARABLE_RESEND_PATH = "/nightscout_watch_data_resend";
private static final String WEARABLE_CANCELBOLUS_PATH = "/nightscout_watch_cancel_bolus";
public static final String WEARABLE_CONFIRM_ACTIONSTRING_PATH = "/nightscout_watch_confirmactionstring";
public static final String WEARABLE_INITIATE_ACTIONSTRING_PATH = "/nightscout_watch_initiateactionstring";
private static final String OPEN_SETTINGS_PATH = "/openwearsettings";
private static final String NEW_STATUS_PATH = "/sendstatustowear";
private static final String NEW_PREFERENCES_PATH = "/sendpreferencestowear";
public static final String BASAL_DATA_PATH = "/nightscout_watch_basal";
public static final String BOLUS_PROGRESS_PATH = "/nightscout_watch_bolusprogress";
public static final String ACTION_CONFIRMATION_REQUEST_PATH = "/nightscout_watch_actionconfirmationrequest";
boolean wear_integration = false;
SharedPreferences mPrefs;
private static boolean lastLoopStatus;
private static Logger log = LoggerFactory.getLogger(WatchUpdaterService.class);
@Override
public void onCreate() {
mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
listenForChangeInSettings();
setSettings();
if (wear_integration) {
googleApiConnect();
}
}
public void listenForChangeInSettings() {
WearPlugin.registerWatchUpdaterService(this);
}
public void setSettings() {
wear_integration = WearPlugin.isEnabled();
if (wear_integration) {
googleApiConnect();
}
}
public void googleApiConnect() {
if (googleApiClient != null && (googleApiClient.isConnected() || googleApiClient.isConnecting())) {
googleApiClient.disconnect();
}
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Wearable.API)
.build();
Wearable.MessageApi.addListener(googleApiClient, this);
if (googleApiClient.isConnected()) {
Log.d("WatchUpdater", "API client is connected");
} else {
googleApiClient.connect();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = null;
if (intent != null) {
action = intent.getAction();
}
if (wear_integration) {
if (googleApiClient.isConnected()) {
if (ACTION_RESEND.equals(action)) {
resendData();
} else if (ACTION_OPEN_SETTINGS.equals(action)) {
sendNotification();
} else if (ACTION_SEND_STATUS.equals(action)) {
sendStatus();
} else if (ACTION_SEND_BASALS.equals(action)) {
sendBasals();
} else if (ACTION_SEND_BOLUSPROGRESS.equals(action)) {
sendBolusProgress(intent.getIntExtra("progresspercent", 0), intent.hasExtra("progressstatus") ? intent.getStringExtra("progressstatus") : "");
} else if (ACTION_SEND_ACTIONCONFIRMATIONREQUEST.equals(action)) {
String title = intent.getStringExtra("title");
String message = intent.getStringExtra("message");
String actionstring = intent.getStringExtra("actionstring");
sendActionConfirmationRequest(title, message, actionstring);
} else {
sendData();
}
} else {
googleApiClient.connect();
}
}
return START_STICKY;
}
@Override
public void onConnected(Bundle connectionHint) {
sendData();
}
@Override
public void onMessageReceived(MessageEvent event) {
if (wear_integration) {
if (event != null && event.getPath().equals(WEARABLE_RESEND_PATH)) {
resendData();
}
if (event != null && event.getPath().equals(WEARABLE_CANCELBOLUS_PATH)) {
cancelBolus();
}
if (event != null && event.getPath().equals(WEARABLE_INITIATE_ACTIONSTRING_PATH)) {
String actionstring = new String(event.getData());
log.debug("Wear: " + actionstring);
ActionStringHandler.handleInitiate(actionstring);
}
if (event != null && event.getPath().equals(WEARABLE_CONFIRM_ACTIONSTRING_PATH)) {
String actionstring = new String(event.getData());
log.debug("Wear Confirm: " + actionstring);
ActionStringHandler.handleConfirmation(actionstring);
}
}
}
private void cancelBolus() {
ConfigBuilderPlugin.getActivePump().stopBolusDelivering();
}
private void sendData() {
BgReading lastBG = DatabaseHelper.lastBg();
if (lastBG != null) {
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
if (wear_integration) {
final DataMap dataMap = dataMapSingleBG(lastBG, glucoseStatus);
if (dataMap == null) {
ToastUtils.showToastInUiThread(this, getString(R.string.noprofile));
return;
}
new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient).execute(dataMap);
}
}
}
private DataMap dataMapSingleBG(BgReading lastBG, GlucoseStatus glucoseStatus) {
String units = MainApp.getConfigBuilder().getProfileUnits();
Double lowLine = SafeParse.stringToDouble(mPrefs.getString("low_mark", "0"));
Double highLine = SafeParse.stringToDouble(mPrefs.getString("high_mark", "0"));
//convert to mg/dl
if (!units.equals(Constants.MGDL)) {
lowLine *= Constants.MMOLL_TO_MGDL;
highLine *= Constants.MMOLL_TO_MGDL;
}
if (lowLine < 1) {
lowLine = OverviewPlugin.bgTargetLow;
}
if (highLine < 1) {
highLine = OverviewPlugin.bgTargetHigh;
}
long sgvLevel = 0l;
if (lastBG.value > highLine) {
sgvLevel = 1;
} else if (lastBG.value < lowLine) {
sgvLevel = -1;
}
DataMap dataMap = new DataMap();
dataMap.putString("sgvString", lastBG.valueToUnitsToString(units));
dataMap.putString("glucoseUnits", units);
dataMap.putLong("timestamp", lastBG.date);
if (glucoseStatus == null) {
dataMap.putString("slopeArrow", "");
dataMap.putString("delta", "--");
dataMap.putString("avgDelta", "--");
} else {
dataMap.putString("slopeArrow", slopeArrow(glucoseStatus.delta));
dataMap.putString("delta", deltastring(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units));
dataMap.putString("avgDelta", deltastring(glucoseStatus.avgdelta, glucoseStatus.avgdelta * Constants.MGDL_TO_MMOLL, units));
}
dataMap.putLong("sgvLevel", sgvLevel);
dataMap.putDouble("sgvDouble", lastBG.value);
dataMap.putDouble("high", highLine);
dataMap.putDouble("low", lowLine);
return dataMap;
}
private String deltastring(double deltaMGDL, double deltaMMOL, String units) {
String deltastring = "";
if (deltaMGDL >= 0) {
deltastring += "+";
} else {
deltastring += "-";
}
boolean detailed = SP.getBoolean("wear_detailed_delta", false);
if (units.equals(Constants.MGDL)) {
if (detailed) {
deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMGDL));
} else {
deltastring += DecimalFormatter.to0Decimal(Math.abs(deltaMGDL));
}
} else {
if (detailed){
deltastring += DecimalFormatter.to2Decimal(Math.abs(deltaMMOL));
} else {
deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMMOL));
}
}
return deltastring;
}
private String slopeArrow(double delta) {
if (delta <= (-3.5 * 5)) {
return "\u21ca";
} else if (delta <= (-2 * 5)) {
return "\u2193";
} else if (delta <= (-1 * 5)) {
return "\u2198";
} else if (delta <= (1 * 5)) {
return "\u2192";
} else if (delta <= (2 * 5)) {
return "\u2197";
} else if (delta <= (3.5 * 5)) {
return "\u2191";
} else {
return "\u21c8";
}
}
private void resendData() {
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
long startTime = System.currentTimeMillis() - (long) (60000 * 60 * 5.5);
BgReading last_bg = DatabaseHelper.lastBg();
if (last_bg == null) return;
List<BgReading> graph_bgs = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, true);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(true);
if (!graph_bgs.isEmpty()) {
DataMap entries = dataMapSingleBG(last_bg, glucoseStatus);
if (entries == null) {
ToastUtils.showToastInUiThread(this, getString(R.string.noprofile));
return;
}
final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
for (BgReading bg : graph_bgs) {
DataMap dataMap = dataMapSingleBG(bg, glucoseStatus);
if (dataMap != null) {
dataMaps.add(dataMap);
}
}
entries.putDataMapArrayList("entries", dataMaps);
new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient).execute(entries);
}
sendPreferences();
sendBasals();
sendStatus();
}
private void sendBasals() {
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
long now = System.currentTimeMillis();
final long startTimeWindow = now - (long) (60000 * 60 * 5.5);
ArrayList<DataMap> basals = new ArrayList<>();
ArrayList<DataMap> temps = new ArrayList<>();
ArrayList<DataMap> boluses = new ArrayList<>();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
return;
}
long beginBasalSegmentTime = startTimeWindow;
long runningTime = startTimeWindow;
double beginBasalValue = profile.getBasal(beginBasalSegmentTime);
double endBasalValue = beginBasalValue;
TemporaryBasal tb1 = MainApp.getConfigBuilder().getTempBasalFromHistory(runningTime);
TemporaryBasal tb2 = MainApp.getConfigBuilder().getTempBasalFromHistory(runningTime);
double tb_before = beginBasalValue;
double tb_amount = beginBasalValue;
long tb_start = runningTime;
if (tb1 != null) {
tb_before = beginBasalValue;
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime);
tb_start = runningTime;
}
for (; runningTime < now; runningTime += 5 * 60 * 1000) {
//basal rate
endBasalValue = profile.getBasal(runningTime);
if (endBasalValue != beginBasalValue) {
//push the segment we recently left
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
//begin new Basal segment
beginBasalSegmentTime = runningTime;
beginBasalValue = endBasalValue;
}
//temps
tb2 = MainApp.getConfigBuilder().getTempBasalFromHistory(runningTime);
if (tb1 == null && tb2 == null) {
//no temp stays no temp
} else if (tb1 != null && tb2 == null) {
//temp is over -> push it
temps.add(tempDatamap(tb_start, tb_before, runningTime, endBasalValue, tb_amount));
tb1 = null;
} else if (tb1 == null && tb2 != null) {
//temp begins
tb1 = tb2;
tb_start = runningTime;
tb_before = endBasalValue;
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime);
} else if (tb1 != null && tb2 != null) {
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime);
if (currentAmount != tb_amount) {
temps.add(tempDatamap(tb_start, tb_before, runningTime, currentAmount, tb_amount));
tb_start = runningTime;
tb_before = tb_amount;
tb_amount = currentAmount;
tb1 = tb2;
}
}
}
if (beginBasalSegmentTime != runningTime) {
//push the remaining segment
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
}
if (tb1 != null) {
tb2 = MainApp.getConfigBuilder().getTempBasalFromHistory(now); //use "now" to express current situation
if (tb2 == null) {
//express the cancelled temp by painting it down one minute early
temps.add(tempDatamap(tb_start, tb_before, now - 1 * 60 * 1000, endBasalValue, tb_amount));
} else {
//express currently running temp by painting it a bit into the future
double currentAmount = tb2.tempBasalConvertedToAbsolute(now);
if (currentAmount != tb_amount) {
temps.add(tempDatamap(tb_start, tb_before, now, tb_amount, tb_amount));
temps.add(tempDatamap(now, tb_amount, runningTime + 5 * 60 * 1000, currentAmount, currentAmount));
} else {
temps.add(tempDatamap(tb_start, tb_before, runningTime + 5 * 60 * 1000, tb_amount, tb_amount));
}
}
} else {
tb2 = MainApp.getConfigBuilder().getTempBasalFromHistory(now); //use "now" to express current situation
if (tb2 != null) {
//onset at the end
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime);
temps.add(tempDatamap(now - 1 * 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount));
}
}
List<Treatment> treatments = MainApp.getConfigBuilder().getTreatmentsFromHistory();
for (Treatment treatment:treatments) {
if(treatment.date > startTimeWindow){
boluses.add(treatmentMap(treatment.date, treatment.insulin, treatment.carbs, treatment.isSMB));
}
}
DataMap dm = new DataMap();
dm.putDataMapArrayList("basals", basals);
dm.putDataMapArrayList("temps", temps);
dm.putDataMapArrayList("boluses", boluses);
new SendToDataLayerThread(BASAL_DATA_PATH, googleApiClient).execute(dm);
}
private DataMap tempDatamap(long startTime, double startBasal, long to, double toBasal, double amount) {
DataMap dm = new DataMap();
dm.putLong("starttime", startTime);
dm.putDouble("startBasal", startBasal);
dm.putLong("endtime", to);
dm.putDouble("endbasal", toBasal);
dm.putDouble("amount", amount);
return dm;
}
private DataMap basalMap(long startTime, long endTime, double amount) {
DataMap dm = new DataMap();
dm.putLong("starttime", startTime);
dm.putLong("endtime", endTime);
dm.putDouble("amount", amount);
return dm;
}
private DataMap treatmentMap(long date, double bolus, double carbs, boolean isSMB) {
DataMap dm = new DataMap();
dm.putLong("date", date);
dm.putDouble("bolus", bolus);
dm.putDouble("carbs", carbs);
dm.putBoolean("isSMB", isSMB);
return dm;
}
private void sendNotification() {
if (googleApiClient.isConnected()) {
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(OPEN_SETTINGS_PATH);
//unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putString("openSettings", "openSettings");
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("OpenSettings", "No connection to wearable available!");
}
}
private void sendBolusProgress(int progresspercent, String status) {
if (googleApiClient.isConnected()) {
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(BOLUS_PROGRESS_PATH);
//unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putString("bolusProgress", "bolusProgress");
dataMapRequest.getDataMap().putString("progressstatus", status);
dataMapRequest.getDataMap().putInt("progresspercent", progresspercent);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("BolusProgress", "No connection to wearable available!");
}
}
private void sendActionConfirmationRequest(String title, String message, String actionstring) {
if (googleApiClient.isConnected()) {
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CONFIRMATION_REQUEST_PATH);
//unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putString("actionConfirmationRequest", "actionConfirmationRequest");
dataMapRequest.getDataMap().putString("title", title);
dataMapRequest.getDataMap().putString("message", message);
dataMapRequest.getDataMap().putString("actionstring", actionstring);
log.debug("Requesting confirmation from wear: " + actionstring);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("confirmationRequest", "No connection to wearable available!");
}
}
private void sendStatus() {
if (googleApiClient.isConnected()) {
Profile profile = MainApp.getConfigBuilder().getProfile();
String status = MainApp.instance().getString(R.string.noprofile);
String iobSum, iobDetail, cobString, currentBasal, bgiString;
iobSum = iobDetail = cobString = currentBasal = bgiString = "";
if(profile!=null) {
TreatmentsInterface treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.updateTotalIOBTreatments();
IobTotal bolusIob = treatmentsInterface.getLastCalculationTreatments().round();
treatmentsInterface.updateTotalIOBTempBasals();
IobTotal basalIob = treatmentsInterface.getLastCalculationTempBasals().round();
iobSum = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob);
iobDetail = "(" + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
cobString = generateCOBString();
currentBasal = generateBasalString(treatmentsInterface);
//bgi
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf();
bgiString = "" + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to1Decimal(bgi);
status = generateStatusString(profile, currentBasal,iobSum, iobDetail, bgiString);
}
//batteries
int phoneBattery = getBatteryLevel(getApplicationContext());
String rigBattery = NSDeviceStatus.getInstance().getUploaderStatus().trim();
long openApsStatus = -1;
//OpenAPS status
if(Config.APS){
//we are AndroidAPS
openApsStatus = LoopPlugin.lastRun != null && LoopPlugin.lastRun.lastEnact != null && LoopPlugin.lastRun.lastEnact.getTime() != 0 ? LoopPlugin.lastRun.lastEnact.getTime(): -1;
} else {
//NSClient or remote
openApsStatus = NSDeviceStatus.getOpenApsTimestamp();
}
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_STATUS_PATH);
//unique content
dataMapRequest.getDataMap().putString("externalStatusString", status);
dataMapRequest.getDataMap().putString("iobSum", iobSum);
dataMapRequest.getDataMap().putString("iobDetail", iobDetail);
dataMapRequest.getDataMap().putBoolean("detailedIob", mPrefs.getBoolean("wear_detailediob", false));
dataMapRequest.getDataMap().putString("cob", cobString);
dataMapRequest.getDataMap().putString("currentBasal", currentBasal);
dataMapRequest.getDataMap().putString("battery", "" + phoneBattery);
dataMapRequest.getDataMap().putString("rigBattery", rigBattery);
dataMapRequest.getDataMap().putLong("openApsStatus", openApsStatus);
dataMapRequest.getDataMap().putString("bgi", bgiString);
dataMapRequest.getDataMap().putBoolean("showBgi", mPrefs.getBoolean("wear_showbgi", false));
dataMapRequest.getDataMap().putInt("batteryLevel", (phoneBattery >= 30) ? 1 : 0);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("SendStatus", "No connection to wearable available!");
}
}
private void sendPreferences() {
if (googleApiClient.isConnected()) {
boolean wearcontrol = SP.getBoolean("wearcontrol", false);
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_PREFERENCES_PATH);
//unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putBoolean("wearcontrol", wearcontrol);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("SendStatus", "No connection to wearable available!");
}
}
@NonNull
private String generateStatusString(Profile profile, String currentBasal, String iobSum, String iobDetail, String bgiString) {
String status = "";
if (profile == null) {
status = MainApp.sResources.getString(R.string.noprofile);
return status;
}
LoopPlugin activeloop = MainApp.getConfigBuilder().getActiveLoop();
if (activeloop != null && !activeloop.isEnabled(PluginBase.LOOP)) {
status += getString(R.string.disabledloop) + "\n";
lastLoopStatus = false;
} else if (activeloop != null && activeloop.isEnabled(PluginBase.LOOP)) {
lastLoopStatus = true;
}
String iobString = "";
if (mPrefs.getBoolean("wear_detailediob", false)) {
iobString = iobSum + " " + iobDetail;
} else {
iobString = iobSum + "U";
}
status += currentBasal + " " + iobString;
//add BGI if shown, otherwise return
if (mPrefs.getBoolean("wear_showbgi", false)) {
status += " " + bgiString;
}
return status;
}
@NonNull
private String generateBasalString(TreatmentsInterface treatmentsInterface) {
String basalStringResult;
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null)
return "";
TemporaryBasal activeTemp = treatmentsInterface.getTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp != null) {
basalStringResult = activeTemp.toStringShort();
} else {
if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false)) {
basalStringResult = "100%";
} else {
basalStringResult = DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h";
}
}
return basalStringResult;
}
@NonNull
private String generateCOBString() {
String cobStringResult = "--";
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensData("WatcherUpdaterService");
if (autosensData != null) {
cobStringResult = (int) autosensData.cob + "g";
}
return cobStringResult;
}
@Override
public void onDestroy() {
if (googleApiClient != null && googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
WearPlugin.unRegisterWatchUpdaterService();
}
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static boolean shouldReportLoopStatus(boolean enabled) {
return (lastLoopStatus != enabled);
}
public static int getBatteryLevel(Context context) {
Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level == -1 || scale == -1) {
return 50;
}
return (int) (((float) level / (float) scale) * 100.0f);
}
}
| app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java | package info.nightscout.androidaps.plugins.Wear.wearintegration;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.Wear.WearPlugin;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
public class WatchUpdaterService extends WearableListenerService implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
public static final String ACTION_RESEND = WatchUpdaterService.class.getName().concat(".Resend");
public static final String ACTION_OPEN_SETTINGS = WatchUpdaterService.class.getName().concat(".OpenSettings");
public static final String ACTION_SEND_STATUS = WatchUpdaterService.class.getName().concat(".SendStatus");
public static final String ACTION_SEND_BASALS = WatchUpdaterService.class.getName().concat(".SendBasals");
public static final String ACTION_SEND_BOLUSPROGRESS = WatchUpdaterService.class.getName().concat(".BolusProgress");
public static final String ACTION_SEND_ACTIONCONFIRMATIONREQUEST = WatchUpdaterService.class.getName().concat(".ActionConfirmationRequest");
private GoogleApiClient googleApiClient;
public static final String WEARABLE_DATA_PATH = "/nightscout_watch_data";
public static final String WEARABLE_RESEND_PATH = "/nightscout_watch_data_resend";
private static final String WEARABLE_CANCELBOLUS_PATH = "/nightscout_watch_cancel_bolus";
public static final String WEARABLE_CONFIRM_ACTIONSTRING_PATH = "/nightscout_watch_confirmactionstring";
public static final String WEARABLE_INITIATE_ACTIONSTRING_PATH = "/nightscout_watch_initiateactionstring";
private static final String OPEN_SETTINGS_PATH = "/openwearsettings";
private static final String NEW_STATUS_PATH = "/sendstatustowear";
private static final String NEW_PREFERENCES_PATH = "/sendpreferencestowear";
public static final String BASAL_DATA_PATH = "/nightscout_watch_basal";
public static final String BOLUS_PROGRESS_PATH = "/nightscout_watch_bolusprogress";
public static final String ACTION_CONFIRMATION_REQUEST_PATH = "/nightscout_watch_actionconfirmationrequest";
boolean wear_integration = false;
SharedPreferences mPrefs;
private static boolean lastLoopStatus;
private static Logger log = LoggerFactory.getLogger(WatchUpdaterService.class);
@Override
public void onCreate() {
mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
listenForChangeInSettings();
setSettings();
if (wear_integration) {
googleApiConnect();
}
}
public void listenForChangeInSettings() {
WearPlugin.registerWatchUpdaterService(this);
}
public void setSettings() {
wear_integration = WearPlugin.isEnabled();
if (wear_integration) {
googleApiConnect();
}
}
public void googleApiConnect() {
if (googleApiClient != null && (googleApiClient.isConnected() || googleApiClient.isConnecting())) {
googleApiClient.disconnect();
}
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Wearable.API)
.build();
Wearable.MessageApi.addListener(googleApiClient, this);
if (googleApiClient.isConnected()) {
Log.d("WatchUpdater", "API client is connected");
} else {
googleApiClient.connect();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = null;
if (intent != null) {
action = intent.getAction();
}
if (wear_integration) {
if (googleApiClient.isConnected()) {
if (ACTION_RESEND.equals(action)) {
resendData();
} else if (ACTION_OPEN_SETTINGS.equals(action)) {
sendNotification();
} else if (ACTION_SEND_STATUS.equals(action)) {
sendStatus();
} else if (ACTION_SEND_BASALS.equals(action)) {
sendBasals();
} else if (ACTION_SEND_BOLUSPROGRESS.equals(action)) {
sendBolusProgress(intent.getIntExtra("progresspercent", 0), intent.hasExtra("progressstatus") ? intent.getStringExtra("progressstatus") : "");
} else if (ACTION_SEND_ACTIONCONFIRMATIONREQUEST.equals(action)) {
String title = intent.getStringExtra("title");
String message = intent.getStringExtra("message");
String actionstring = intent.getStringExtra("actionstring");
sendActionConfirmationRequest(title, message, actionstring);
} else {
sendData();
}
} else {
googleApiClient.connect();
}
}
return START_STICKY;
}
@Override
public void onConnected(Bundle connectionHint) {
sendData();
}
@Override
public void onMessageReceived(MessageEvent event) {
if (wear_integration) {
if (event != null && event.getPath().equals(WEARABLE_RESEND_PATH)) {
resendData();
}
if (event != null && event.getPath().equals(WEARABLE_CANCELBOLUS_PATH)) {
cancelBolus();
}
if (event != null && event.getPath().equals(WEARABLE_INITIATE_ACTIONSTRING_PATH)) {
String actionstring = new String(event.getData());
log.debug("Wear: " + actionstring);
ActionStringHandler.handleInitiate(actionstring);
}
if (event != null && event.getPath().equals(WEARABLE_CONFIRM_ACTIONSTRING_PATH)) {
String actionstring = new String(event.getData());
log.debug("Wear Confirm: " + actionstring);
ActionStringHandler.handleConfirmation(actionstring);
}
}
}
private void cancelBolus() {
ConfigBuilderPlugin.getActivePump().stopBolusDelivering();
}
private void sendData() {
BgReading lastBG = DatabaseHelper.lastBg();
if (lastBG != null) {
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
if (wear_integration) {
final DataMap dataMap = dataMapSingleBG(lastBG, glucoseStatus);
if (dataMap == null) {
ToastUtils.showToastInUiThread(this, getString(R.string.noprofile));
return;
}
new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient).execute(dataMap);
}
}
}
private DataMap dataMapSingleBG(BgReading lastBG, GlucoseStatus glucoseStatus) {
String units = MainApp.getConfigBuilder().getProfileUnits();
Double lowLine = SafeParse.stringToDouble(mPrefs.getString("low_mark", "0"));
Double highLine = SafeParse.stringToDouble(mPrefs.getString("high_mark", "0"));
//convert to mg/dl
if (!units.equals(Constants.MGDL)) {
lowLine *= Constants.MMOLL_TO_MGDL;
highLine *= Constants.MMOLL_TO_MGDL;
}
if (lowLine < 1) {
lowLine = OverviewPlugin.bgTargetLow;
}
if (highLine < 1) {
highLine = OverviewPlugin.bgTargetHigh;
}
long sgvLevel = 0l;
if (lastBG.value > highLine) {
sgvLevel = 1;
} else if (lastBG.value < lowLine) {
sgvLevel = -1;
}
DataMap dataMap = new DataMap();
dataMap.putString("sgvString", lastBG.valueToUnitsToString(units));
dataMap.putString("glucoseUnits", units);
dataMap.putLong("timestamp", lastBG.date);
if (glucoseStatus == null) {
dataMap.putString("slopeArrow", "");
dataMap.putString("delta", "--");
dataMap.putString("avgDelta", "--");
} else {
dataMap.putString("slopeArrow", slopeArrow(glucoseStatus.delta));
dataMap.putString("delta", deltastring(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units));
dataMap.putString("avgDelta", deltastring(glucoseStatus.avgdelta, glucoseStatus.avgdelta * Constants.MGDL_TO_MMOLL, units));
}
dataMap.putLong("sgvLevel", sgvLevel);
dataMap.putDouble("sgvDouble", lastBG.value);
dataMap.putDouble("high", highLine);
dataMap.putDouble("low", lowLine);
return dataMap;
}
private String deltastring(double deltaMGDL, double deltaMMOL, String units) {
String deltastring = "";
if (deltaMGDL >= 0) {
deltastring += "+";
} else {
deltastring += "-";
}
boolean detailed = SP.getBoolean("wear_detailed_delta", false);
if (units.equals(Constants.MGDL)) {
if (detailed) {
deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMGDL));
} else {
deltastring += DecimalFormatter.to0Decimal(Math.abs(deltaMGDL));
}
} else {
if (detailed){
deltastring += DecimalFormatter.to2Decimal(Math.abs(deltaMMOL));
} else {
deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMMOL));
}
}
return deltastring;
}
private String slopeArrow(double delta) {
if (delta <= (-3.5 * 5)) {
return "\u21ca";
} else if (delta <= (-2 * 5)) {
return "\u2193";
} else if (delta <= (-1 * 5)) {
return "\u2198";
} else if (delta <= (1 * 5)) {
return "\u2192";
} else if (delta <= (2 * 5)) {
return "\u2197";
} else if (delta <= (3.5 * 5)) {
return "\u2191";
} else {
return "\u21c8";
}
}
private void resendData() {
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
long startTime = System.currentTimeMillis() - (long) (60000 * 60 * 5.5);
BgReading last_bg = DatabaseHelper.lastBg();
if (last_bg == null) return;
List<BgReading> graph_bgs = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, true);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(true);
if (!graph_bgs.isEmpty()) {
DataMap entries = dataMapSingleBG(last_bg, glucoseStatus);
if (entries == null) {
ToastUtils.showToastInUiThread(this, getString(R.string.noprofile));
return;
}
final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
for (BgReading bg : graph_bgs) {
DataMap dataMap = dataMapSingleBG(bg, glucoseStatus);
if (dataMap != null) {
dataMaps.add(dataMap);
}
}
entries.putDataMapArrayList("entries", dataMaps);
new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient).execute(entries);
}
sendPreferences();
sendBasals();
sendStatus();
}
private void sendBasals() {
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
long now = System.currentTimeMillis();
long startTimeWindow = now - (long) (60000 * 60 * 5.5);
ArrayList<DataMap> basals = new ArrayList<>();
ArrayList<DataMap> temps = new ArrayList<>();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
return;
}
long beginBasalSegmentTime = startTimeWindow;
long runningTime = startTimeWindow;
double beginBasalValue = profile.getBasal(beginBasalSegmentTime);
double endBasalValue = beginBasalValue;
TemporaryBasal tb1 = MainApp.getConfigBuilder().getTempBasalFromHistory(runningTime);
TemporaryBasal tb2 = MainApp.getConfigBuilder().getTempBasalFromHistory(runningTime);
double tb_before = beginBasalValue;
double tb_amount = beginBasalValue;
long tb_start = runningTime;
if (tb1 != null) {
tb_before = beginBasalValue;
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime);
tb_start = runningTime;
}
for (; runningTime < now; runningTime += 5 * 60 * 1000) {
//basal rate
endBasalValue = profile.getBasal(runningTime);
if (endBasalValue != beginBasalValue) {
//push the segment we recently left
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
//begin new Basal segment
beginBasalSegmentTime = runningTime;
beginBasalValue = endBasalValue;
}
//temps
tb2 = MainApp.getConfigBuilder().getTempBasalFromHistory(runningTime);
if (tb1 == null && tb2 == null) {
//no temp stays no temp
} else if (tb1 != null && tb2 == null) {
//temp is over -> push it
temps.add(tempDatamap(tb_start, tb_before, runningTime, endBasalValue, tb_amount));
tb1 = null;
} else if (tb1 == null && tb2 != null) {
//temp begins
tb1 = tb2;
tb_start = runningTime;
tb_before = endBasalValue;
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime);
} else if (tb1 != null && tb2 != null) {
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime);
if (currentAmount != tb_amount) {
temps.add(tempDatamap(tb_start, tb_before, runningTime, currentAmount, tb_amount));
tb_start = runningTime;
tb_before = tb_amount;
tb_amount = currentAmount;
tb1 = tb2;
}
}
}
if (beginBasalSegmentTime != runningTime) {
//push the remaining segment
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
}
if (tb1 != null) {
tb2 = MainApp.getConfigBuilder().getTempBasalFromHistory(now); //use "now" to express current situation
if (tb2 == null) {
//express the cancelled temp by painting it down one minute early
temps.add(tempDatamap(tb_start, tb_before, now - 1 * 60 * 1000, endBasalValue, tb_amount));
} else {
//express currently running temp by painting it a bit into the future
double currentAmount = tb2.tempBasalConvertedToAbsolute(now);
if (currentAmount != tb_amount) {
temps.add(tempDatamap(tb_start, tb_before, now, tb_amount, tb_amount));
temps.add(tempDatamap(now, tb_amount, runningTime + 5 * 60 * 1000, currentAmount, currentAmount));
} else {
temps.add(tempDatamap(tb_start, tb_before, runningTime + 5 * 60 * 1000, tb_amount, tb_amount));
}
}
} else {
tb2 = MainApp.getConfigBuilder().getTempBasalFromHistory(now); //use "now" to express current situation
if (tb2 != null) {
//onset at the end
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime);
temps.add(tempDatamap(now - 1 * 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount));
}
}
DataMap dm = new DataMap();
dm.putDataMapArrayList("basals", basals);
dm.putDataMapArrayList("temps", temps);
new SendToDataLayerThread(BASAL_DATA_PATH, googleApiClient).execute(dm);
}
private DataMap tempDatamap(long startTime, double startBasal, long to, double toBasal, double amount) {
DataMap dm = new DataMap();
dm.putLong("starttime", startTime);
dm.putDouble("startBasal", startBasal);
dm.putLong("endtime", to);
dm.putDouble("endbasal", toBasal);
dm.putDouble("amount", amount);
return dm;
}
private DataMap basalMap(long startTime, long endTime, double amount) {
DataMap dm = new DataMap();
dm.putLong("starttime", startTime);
dm.putLong("endtime", endTime);
dm.putDouble("amount", amount);
return dm;
}
private void sendNotification() {
if (googleApiClient.isConnected()) {
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(OPEN_SETTINGS_PATH);
//unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putString("openSettings", "openSettings");
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("OpenSettings", "No connection to wearable available!");
}
}
private void sendBolusProgress(int progresspercent, String status) {
if (googleApiClient.isConnected()) {
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(BOLUS_PROGRESS_PATH);
//unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putString("bolusProgress", "bolusProgress");
dataMapRequest.getDataMap().putString("progressstatus", status);
dataMapRequest.getDataMap().putInt("progresspercent", progresspercent);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("BolusProgress", "No connection to wearable available!");
}
}
private void sendActionConfirmationRequest(String title, String message, String actionstring) {
if (googleApiClient.isConnected()) {
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CONFIRMATION_REQUEST_PATH);
//unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putString("actionConfirmationRequest", "actionConfirmationRequest");
dataMapRequest.getDataMap().putString("title", title);
dataMapRequest.getDataMap().putString("message", message);
dataMapRequest.getDataMap().putString("actionstring", actionstring);
log.debug("Requesting confirmation from wear: " + actionstring);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("confirmationRequest", "No connection to wearable available!");
}
}
private void sendStatus() {
if (googleApiClient.isConnected()) {
Profile profile = MainApp.getConfigBuilder().getProfile();
String status = MainApp.instance().getString(R.string.noprofile);
String iobSum, iobDetail, cobString, currentBasal, bgiString;
iobSum = iobDetail = cobString = currentBasal = bgiString = "";
if(profile!=null) {
TreatmentsInterface treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.updateTotalIOBTreatments();
IobTotal bolusIob = treatmentsInterface.getLastCalculationTreatments().round();
treatmentsInterface.updateTotalIOBTempBasals();
IobTotal basalIob = treatmentsInterface.getLastCalculationTempBasals().round();
iobSum = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob);
iobDetail = "(" + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
cobString = generateCOBString();
currentBasal = generateBasalString(treatmentsInterface);
//bgi
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf();
bgiString = "" + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to1Decimal(bgi);
status = generateStatusString(profile, currentBasal,iobSum, iobDetail, bgiString);
}
//batteries
int phoneBattery = getBatteryLevel(getApplicationContext());
String rigBattery = NSDeviceStatus.getInstance().getUploaderStatus().trim();
long openApsStatus = -1;
//OpenAPS status
if(Config.APS){
//we are AndroidAPS
openApsStatus = LoopPlugin.lastRun != null && LoopPlugin.lastRun.lastEnact != null && LoopPlugin.lastRun.lastEnact.getTime() != 0 ? LoopPlugin.lastRun.lastEnact.getTime(): -1;
} else {
//NSClient or remote
openApsStatus = NSDeviceStatus.getOpenApsTimestamp();
}
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_STATUS_PATH);
//unique content
dataMapRequest.getDataMap().putString("externalStatusString", status);
dataMapRequest.getDataMap().putString("iobSum", iobSum);
dataMapRequest.getDataMap().putString("iobDetail", iobDetail);
dataMapRequest.getDataMap().putBoolean("detailedIob", mPrefs.getBoolean("wear_detailediob", false));
dataMapRequest.getDataMap().putString("cob", cobString);
dataMapRequest.getDataMap().putString("currentBasal", currentBasal);
dataMapRequest.getDataMap().putString("battery", "" + phoneBattery);
dataMapRequest.getDataMap().putString("rigBattery", rigBattery);
dataMapRequest.getDataMap().putLong("openApsStatus", openApsStatus);
dataMapRequest.getDataMap().putString("bgi", bgiString);
dataMapRequest.getDataMap().putBoolean("showBgi", mPrefs.getBoolean("wear_showbgi", false));
dataMapRequest.getDataMap().putInt("batteryLevel", (phoneBattery >= 30) ? 1 : 0);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("SendStatus", "No connection to wearable available!");
}
}
private void sendPreferences() {
if (googleApiClient.isConnected()) {
boolean wearcontrol = SP.getBoolean("wearcontrol", false);
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_PREFERENCES_PATH);
//unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putBoolean("wearcontrol", wearcontrol);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("SendStatus", "No connection to wearable available!");
}
}
@NonNull
private String generateStatusString(Profile profile, String currentBasal, String iobSum, String iobDetail, String bgiString) {
String status = "";
if (profile == null) {
status = MainApp.sResources.getString(R.string.noprofile);
return status;
}
LoopPlugin activeloop = MainApp.getConfigBuilder().getActiveLoop();
if (activeloop != null && !activeloop.isEnabled(PluginBase.LOOP)) {
status += getString(R.string.disabledloop) + "\n";
lastLoopStatus = false;
} else if (activeloop != null && activeloop.isEnabled(PluginBase.LOOP)) {
lastLoopStatus = true;
}
String iobString = "";
if (mPrefs.getBoolean("wear_detailediob", false)) {
iobString = iobSum + " " + iobDetail;
} else {
iobString = iobSum + "U";
}
status += currentBasal + " " + iobString;
//add BGI if shown, otherwise return
if (mPrefs.getBoolean("wear_showbgi", false)) {
status += " " + bgiString;
}
return status;
}
@NonNull
private String generateBasalString(TreatmentsInterface treatmentsInterface) {
String basalStringResult;
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null)
return "";
TemporaryBasal activeTemp = treatmentsInterface.getTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp != null) {
basalStringResult = activeTemp.toStringShort();
} else {
if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false)) {
basalStringResult = "100%";
} else {
basalStringResult = DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h";
}
}
return basalStringResult;
}
@NonNull
private String generateCOBString() {
String cobStringResult = "--";
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensData("WatcherUpdaterService");
if (autosensData != null) {
cobStringResult = (int) autosensData.cob + "g";
}
return cobStringResult;
}
@Override
public void onDestroy() {
if (googleApiClient != null && googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
WearPlugin.unRegisterWatchUpdaterService();
}
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static boolean shouldReportLoopStatus(boolean enabled) {
return (lastLoopStatus != enabled);
}
public static int getBatteryLevel(Context context) {
Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level == -1 || scale == -1) {
return 50;
}
return (int) (((float) level / (float) scale) * 100.0f);
}
}
| add boluses to wear payload
| app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java | add boluses to wear payload | <ide><path>pp/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java
<ide> import com.google.android.gms.wearable.Wearable;
<ide> import com.google.android.gms.wearable.WearableListenerService;
<ide>
<add>import org.mozilla.javascript.tools.jsc.Main;
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.LinkedList;
<ide> import java.util.List;
<add>import java.util.stream.Collectors;
<ide>
<ide> import info.nightscout.androidaps.Config;
<ide> import info.nightscout.androidaps.Constants;
<ide> import info.nightscout.androidaps.db.BgReading;
<ide> import info.nightscout.androidaps.db.DatabaseHelper;
<ide> import info.nightscout.androidaps.db.TemporaryBasal;
<add>import info.nightscout.androidaps.db.Treatment;
<ide> import info.nightscout.androidaps.interfaces.PluginBase;
<ide> import info.nightscout.androidaps.interfaces.TreatmentsInterface;
<ide> import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
<ide> }
<ide>
<ide> long now = System.currentTimeMillis();
<del> long startTimeWindow = now - (long) (60000 * 60 * 5.5);
<add> final long startTimeWindow = now - (long) (60000 * 60 * 5.5);
<ide>
<ide>
<ide> ArrayList<DataMap> basals = new ArrayList<>();
<ide> ArrayList<DataMap> temps = new ArrayList<>();
<add> ArrayList<DataMap> boluses = new ArrayList<>();
<add>
<ide>
<ide>
<ide> Profile profile = MainApp.getConfigBuilder().getProfile();
<ide> }
<ide> }
<ide>
<add> List<Treatment> treatments = MainApp.getConfigBuilder().getTreatmentsFromHistory();
<add> for (Treatment treatment:treatments) {
<add> if(treatment.date > startTimeWindow){
<add> boluses.add(treatmentMap(treatment.date, treatment.insulin, treatment.carbs, treatment.isSMB));
<add> }
<add>
<add> }
<ide> DataMap dm = new DataMap();
<ide> dm.putDataMapArrayList("basals", basals);
<ide> dm.putDataMapArrayList("temps", temps);
<add> dm.putDataMapArrayList("boluses", boluses);
<ide>
<ide> new SendToDataLayerThread(BASAL_DATA_PATH, googleApiClient).execute(dm);
<ide> }
<ide> dm.putLong("starttime", startTime);
<ide> dm.putLong("endtime", endTime);
<ide> dm.putDouble("amount", amount);
<add> return dm;
<add> }
<add>
<add> private DataMap treatmentMap(long date, double bolus, double carbs, boolean isSMB) {
<add> DataMap dm = new DataMap();
<add> dm.putLong("date", date);
<add> dm.putDouble("bolus", bolus);
<add> dm.putDouble("carbs", carbs);
<add> dm.putBoolean("isSMB", isSMB);
<ide> return dm;
<ide> }
<ide> |
|
JavaScript | mit | 3997d7c3092f7366398da5380a7f1ce503ee8556 | 0 | hansmaad/chartist-js,cr3ative/chartist-js,cr3ative/chartist-js,gionkunz/chartist-js,chartist-js/chartist,chartist-js/chartist,chartist-js/chartist,gionkunz/chartist-js,hansmaad/chartist-js | /**
* The core module of Chartist that is mainly providing static functions and higher level functions for chart modules.
*
* @module Chartist.Core
*/
var Chartist = {};
Chartist.version = '0.3.1';
(function (window, document, Chartist) {
'use strict';
/**
* Helps to simplify functional style code
*
* @memberof Chartist.Core
* @param {*} n This exact value will be returned by the noop function
* @return {*} The same value that was provided to the n parameter
*/
Chartist.noop = function (n) {
return n;
};
/**
* Generates a-z from a number 0 to 26
*
* @memberof Chartist.Core
* @param {Number} n A number from 0 to 26 that will result in a letter a-z
* @return {String} A character from a-z based on the input number n
*/
Chartist.alphaNumerate = function (n) {
// Limit to a-z
return String.fromCharCode(97 + n % 26);
};
// TODO: Make it possible to call extend with var args
/**
* Simple recursive object extend
*
* @memberof Chartist.Core
* @param {Object} target Target object where the source will be merged into
* @param {Object} source This object will be merged into target and then target is returned
* @return {Object} An object that has the same reference as target but is extended and merged with the properties of source
*/
Chartist.extend = function (target, source) {
target = target || {};
for (var prop in source) {
if (typeof source[prop] === 'object') {
target[prop] = Chartist.extend(target[prop], source[prop]);
} else {
target[prop] = source[prop];
}
}
return target;
};
/**
* Converts a string to a number while removing the unit px if present. If a number is passed then this will be returned unmodified.
*
* @param {String|Number} length
* @returns {Number} Returns the pixel as number or NaN if the passed length could not be converted to pixel
*/
Chartist.getPixelLength = function(length) {
if(typeof length === 'string') {
length = length.replace(/px/i, '');
}
return +length;
};
/**
* This is a wrapper around document.querySelector that will return the query if it's already of type Node
*
* @memberof Chartist.Core
* @param {String|Node} query The query to use for selecting a Node or a DOM node that will be returned directly
* @return {Node}
*/
Chartist.querySelector = function(query) {
return query instanceof Node ? query : document.querySelector(query);
};
/**
* Create or reinitialize the SVG element for the chart
*
* @memberof Chartist.Core
* @param {Node} container The containing DOM Node object that will be used to plant the SVG element
* @param {String} width Set the width of the SVG element. Default is 100%
* @param {String} height Set the height of the SVG element. Default is 100%
* @param {String} className Specify a class to be added to the SVG element
* @return {Object} The created/reinitialized SVG element
*/
Chartist.createSvg = function (container, width, height, className) {
var svg;
width = width || '100%';
height = height || '100%';
// If already contains our svg object we clear it, set width / height and return
if (container.__chartist__ && container.__chartist__.svg) {
svg = container.__chartist__.svg.attr({
width: width,
height: height
}).removeAllClasses().addClass(className).attr({
style: 'width: ' + width + '; height: ' + height + ';'
});
// Clear the draw if its already used before so we start fresh
svg.empty();
} else {
// Create svg object with width and height or use 100% as default
svg = Chartist.Svg('svg').attr({
width: width,
height: height
}).addClass(className).attr({
style: 'width: ' + width + '; height: ' + height + ';'
});
// Add the DOM node to our container
container.appendChild(svg._node);
}
return svg;
};
/**
* Convert data series into plain array
*
* @memberof Chartist.Core
* @param {Object} data The series object that contains the data to be visualized in the chart
* @return {Array} A plain array that contains the data to be visualized in the chart
*/
Chartist.getDataArray = function (data) {
var array = [];
for (var i = 0; i < data.series.length; i++) {
// If the series array contains an object with a data property we will use the property
// otherwise the value directly (array or number)
array[i] = typeof(data.series[i]) === 'object' && data.series[i].data !== undefined ?
data.series[i].data : data.series[i];
// Convert values to number
for (var j = 0; j < array[i].length; j++) {
array[i][j] = +array[i][j];
}
}
return array;
};
/**
* Adds missing values at the end of the array. This array contains the data, that will be visualized in the chart
*
* @memberof Chartist.Core
* @param {Array} dataArray The array that contains the data to be visualized in the chart. The array in this parameter will be modified by function.
* @param {Number} length The length of the x-axis data array.
* @return {Array} The array that got updated with missing values.
*/
Chartist.normalizeDataArray = function (dataArray, length) {
for (var i = 0; i < dataArray.length; i++) {
if (dataArray[i].length === length) {
continue;
}
for (var j = dataArray[i].length; j < length; j++) {
dataArray[i][j] = 0;
}
}
return dataArray;
};
/**
* Calculate the order of magnitude for the chart scale
*
* @memberof Chartist.Core
* @param {Number} value The value Range of the chart
* @return {Number} The order of magnitude
*/
Chartist.orderOfMagnitude = function (value) {
return Math.floor(Math.log(Math.abs(value)) / Math.LN10);
};
/**
* Project a data length into screen coordinates (pixels)
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Number} length Single data value from a series array
* @param {Object} bounds All the values to set the bounds of the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @return {Number} The projected data length in pixels
*/
Chartist.projectLength = function (svg, length, bounds, options) {
var availableHeight = Chartist.getAvailableHeight(svg, options);
return (length / bounds.range * availableHeight);
};
/**
* Get the height of the area in the chart for the data series
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @return {Number} The height of the area in the chart for the data series
*/
Chartist.getAvailableHeight = function (svg, options) {
return Math.max((Chartist.getPixelLength(options.height) || svg.height()) - (options.chartPadding * 2) - options.axisX.offset, 0);
};
/**
* Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.
*
* @memberof Chartist.Core
* @param {Array} dataArray The array that contains the data to be visualized in the chart
* @return {Array} The array that contains the highest and lowest value that will be visualized on the chart.
*/
Chartist.getHighLow = function (dataArray) {
var i,
j,
highLow = {
high: -Number.MAX_VALUE,
low: Number.MAX_VALUE
};
for (i = 0; i < dataArray.length; i++) {
for (j = 0; j < dataArray[i].length; j++) {
if (dataArray[i][j] > highLow.high) {
highLow.high = dataArray[i][j];
}
if (dataArray[i][j] < highLow.low) {
highLow.low = dataArray[i][j];
}
}
}
return highLow;
};
// Find the highest and lowest values in a two dimensional array and calculate scale based on order of magnitude
/**
* Calculate and retrieve all the bounds for the chart and return them in one array
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Array} normalizedData The array that got updated with missing values.
* @param {Object} options The Object that contains all the optional values for the chart
* @param {Number} referenceValue The reference value for the chart.
* @return {Object} All the values to set the bounds of the chart
*/
Chartist.getBounds = function (svg, normalizedData, options, referenceValue) {
var i,
newMin,
newMax,
bounds = Chartist.getHighLow(normalizedData);
// Overrides of high / low from settings
bounds.high = +options.high || (options.high === 0 ? 0 : bounds.high);
bounds.low = +options.low || (options.low === 0 ? 0 : bounds.low);
// If high and low are the same because of misconfiguration or flat data (only the same value) we need
// to set the high or low to 0 depending on the polarity
if(bounds.high === bounds.low) {
// If both values are 0 we set high to 1
if(bounds.low === 0) {
bounds.high = 1;
} else if(bounds.low < 0) {
// If we have the same negative value for the bounds we set bounds.high to 0
bounds.high = 0;
} else {
// If we have the same positive value for the bounds we set bounds.low to 0
bounds.low = 0;
}
}
// Overrides of high / low based on reference value, it will make sure that the invisible reference value is
// used to generate the chart. This is useful when the chart always needs to contain the position of the
// invisible reference value in the view i.e. for bipolar scales.
if (referenceValue || referenceValue === 0) {
bounds.high = Math.max(referenceValue, bounds.high);
bounds.low = Math.min(referenceValue, bounds.low);
}
bounds.valueRange = bounds.high - bounds.low;
bounds.oom = Chartist.orderOfMagnitude(bounds.valueRange);
bounds.min = Math.floor(bounds.low / Math.pow(10, bounds.oom)) * Math.pow(10, bounds.oom);
bounds.max = Math.ceil(bounds.high / Math.pow(10, bounds.oom)) * Math.pow(10, bounds.oom);
bounds.range = bounds.max - bounds.min;
bounds.step = Math.pow(10, bounds.oom);
bounds.numberOfSteps = Math.round(bounds.range / bounds.step);
// Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace
// If we are already below the scaleMinSpace value we will scale up
var length = Chartist.projectLength(svg, bounds.step, bounds, options),
scaleUp = length < options.axisY.scaleMinSpace;
while (true) {
if (scaleUp && Chartist.projectLength(svg, bounds.step, bounds, options) <= options.axisY.scaleMinSpace) {
bounds.step *= 2;
} else if (!scaleUp && Chartist.projectLength(svg, bounds.step / 2, bounds, options) >= options.axisY.scaleMinSpace) {
bounds.step /= 2;
} else {
break;
}
}
// Narrow min and max based on new step
newMin = bounds.min;
newMax = bounds.max;
for (i = bounds.min; i <= bounds.max; i += bounds.step) {
if (i + bounds.step < bounds.low) {
newMin += bounds.step;
}
if (i - bounds.step > bounds.high) {
newMax -= bounds.step;
}
}
bounds.min = newMin;
bounds.max = newMax;
bounds.range = bounds.max - bounds.min;
bounds.values = [];
for (i = bounds.min; i <= bounds.max; i += bounds.step) {
bounds.values.push(i);
}
return bounds;
};
/**
* Calculate cartesian coordinates of polar coordinates
*
* @memberof Chartist.Core
* @param {Number} centerX X-axis coordinates of center point of circle segment
* @param {Number} centerY X-axis coordinates of center point of circle segment
* @param {Number} radius Radius of circle segment
* @param {Number} angleInDegrees Angle of circle segment in degrees
* @return {Number} Coordinates of point on circumference
*/
Chartist.polarToCartesian = function (centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
};
/**
* Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @return {Object} The chart rectangles coordinates inside the svg element plus the rectangles measurements
*/
Chartist.createChartRect = function (svg, options) {
var yOffset = options.axisY ? options.axisY.offset : 0,
xOffset = options.axisX ? options.axisX.offset : 0;
return {
x1: options.chartPadding + yOffset,
y1: Math.max((Chartist.getPixelLength(options.height) || svg.height()) - options.chartPadding - xOffset, options.chartPadding),
x2: Math.max((Chartist.getPixelLength(options.width) || svg.width()) - options.chartPadding, options.chartPadding + yOffset),
y2: options.chartPadding,
width: function () {
return this.x2 - this.x1;
},
height: function () {
return this.y1 - this.y2;
}
};
};
/**
* Creates a label with text and based on support of SVG1.1 extensibility will use a foreignObject with a SPAN element or a fallback to a regular SVG text element.
*
* @param {Object} parent The SVG element where the label should be created as a child
* @param {String} text The label text
* @param {Object} attributes An object with all attributes that should be set on the label element
* @param {String} className The class names that should be set for this element
* @param {Boolean} supportsForeignObject If this is true then a foreignObject will be used instead of a text element
* @returns {Object} The newly created SVG element
*/
Chartist.createLabel = function(parent, text, attributes, className, supportsForeignObject) {
if(supportsForeignObject) {
var content = '<span class="' + className + '">' + text + '</span>';
return parent.foreignObject(content, attributes);
} else {
return parent.elem('text', attributes, className).text(text);
}
};
/**
* Generate grid lines and labels for the x-axis into grid and labels group SVG elements
*
* @memberof Chartist.Core
* @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element
* @param {Object} data The Object that contains the data to be visualized in the chart
* @param {Object} grid Chartist.Svg wrapper object to be filled with the grid lines of the chart
* @param {Object} labels Chartist.Svg wrapper object to be filled with the lables of the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @param {Object} eventEmitter The passed event emitter will be used to emit draw events for labels and gridlines
* @param {Boolean} supportsForeignObject If this is true then a foreignObject will be used instead of a text element
*/
Chartist.createXAxis = function (chartRect, data, grid, labels, options, eventEmitter, supportsForeignObject) {
// Create X-Axis
data.labels.forEach(function (value, index) {
var interpolatedValue = options.axisX.labelInterpolationFnc(value, index),
width = chartRect.width() / data.labels.length,
height = options.axisX.offset,
pos = chartRect.x1 + width * index;
// If interpolated value returns falsey (except 0) we don't draw the grid line
if (!interpolatedValue && interpolatedValue !== 0) {
return;
}
if (options.axisX.showGrid) {
var gridElement = grid.elem('line', {
x1: pos,
y1: chartRect.y1,
x2: pos,
y2: chartRect.y2
}, [options.classNames.grid, options.classNames.horizontal].join(' '));
// Event for grid draw
eventEmitter.emit('draw', {
type: 'grid',
axis: 'x',
index: index,
group: grid,
element: gridElement,
x1: pos,
y1: chartRect.y1,
x2: pos,
y2: chartRect.y2
});
}
if (options.axisX.showLabel) {
var labelPosition = {
x: pos + options.axisX.labelOffset.x,
y: chartRect.y1 + options.axisX.labelOffset.y + (supportsForeignObject ? 5 : 20)
};
var labelElement = Chartist.createLabel(labels, '' + interpolatedValue, {
x: labelPosition.x,
y: labelPosition.y,
width: width,
height: height,
style: 'overflow: visible;'
}, [options.classNames.label, options.classNames.horizontal].join(' '), supportsForeignObject);
eventEmitter.emit('draw', {
type: 'label',
axis: 'x',
index: index,
group: labels,
element: labelElement,
text: '' + interpolatedValue,
x: labelPosition.x,
y: labelPosition.y,
width: width,
height: height,
// TODO: Remove in next major release
get space() {
window.console.warn('EventEmitter: space is deprecated, use width or height instead.');
return this.width;
}
});
}
});
};
/**
* Generate grid lines and labels for the y-axis into grid and labels group SVG elements
*
* @memberof Chartist.Core
* @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element
* @param {Object} bounds All the values to set the bounds of the chart
* @param {Object} grid Chartist.Svg wrapper object to be filled with the grid lines of the chart
* @param {Object} labels Chartist.Svg wrapper object to be filled with the lables of the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @param {Object} eventEmitter The passed event emitter will be used to emit draw events for labels and gridlines
* @param {Boolean} supportsForeignObject If this is true then a foreignObject will be used instead of a text element
*/
Chartist.createYAxis = function (chartRect, bounds, grid, labels, options, eventEmitter, supportsForeignObject) {
// Create Y-Axis
bounds.values.forEach(function (value, index) {
var interpolatedValue = options.axisY.labelInterpolationFnc(value, index),
width = options.axisY.offset,
height = chartRect.height() / bounds.values.length,
pos = chartRect.y1 - height * index;
// If interpolated value returns falsey (except 0) we don't draw the grid line
if (!interpolatedValue && interpolatedValue !== 0) {
return;
}
if (options.axisY.showGrid) {
var gridElement = grid.elem('line', {
x1: chartRect.x1,
y1: pos,
x2: chartRect.x2,
y2: pos
}, [options.classNames.grid, options.classNames.vertical].join(' '));
// Event for grid draw
eventEmitter.emit('draw', {
type: 'grid',
axis: 'y',
index: index,
group: grid,
element: gridElement,
x1: chartRect.x1,
y1: pos,
x2: chartRect.x2,
y2: pos
});
}
if (options.axisY.showLabel) {
var labelPosition = {
x: options.chartPadding + options.axisY.labelOffset.x + (supportsForeignObject ? -10 : 0),
y: pos + options.axisY.labelOffset.y + (supportsForeignObject ? -15 : 0)
};
var labelElement = Chartist.createLabel(labels, '' + interpolatedValue, {
x: labelPosition.x,
y: labelPosition.y,
width: width,
height: height,
style: 'overflow: visible;'
}, [options.classNames.label, options.classNames.vertical].join(' '), supportsForeignObject);
eventEmitter.emit('draw', {
type: 'label',
axis: 'y',
index: index,
group: labels,
element: labelElement,
text: '' + interpolatedValue,
x: labelPosition.x,
y: labelPosition.y,
width: width,
height: height,
// TODO: Remove in next major release
get space() {
window.console.warn('EventEmitter: space is deprecated, use width or height instead.');
return this.height;
}
});
}
});
};
/**
* Determine the current point on the svg element to draw the data series
*
* @memberof Chartist.Core
* @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element
* @param {Object} bounds All the values to set the bounds of the chart
* @param {Array} data The array that contains the data to be visualized in the chart
* @param {Number} index The index of the current project point
* @return {Object} The coordinates object of the current project point containing an x and y number property
*/
Chartist.projectPoint = function (chartRect, bounds, data, index) {
return {
x: chartRect.x1 + chartRect.width() / data.length * index,
y: chartRect.y1 - chartRect.height() * (data[index] - bounds.min) / (bounds.range + bounds.step)
};
};
// TODO: With multiple media queries the handleMediaChange function is triggered too many times, only need one
/**
* Provides options handling functionality with callback for options changes triggered by responsive options and media query matches
*
* @memberof Chartist.Core
* @param {Object} defaultOptions Default options from Chartist
* @param {Object} options Options set by user
* @param {Array} responsiveOptions Optional functions to add responsive behavior to chart
* @param {Object} eventEmitter The event emitter that will be used to emit the options changed events
* @return {Object} The consolidated options object from the defaults, base and matching responsive options
*/
Chartist.optionsProvider = function (defaultOptions, options, responsiveOptions, eventEmitter) {
var baseOptions = Chartist.extend(Chartist.extend({}, defaultOptions), options),
currentOptions,
mediaQueryListeners = [],
i;
function updateCurrentOptions() {
var previousOptions = currentOptions;
currentOptions = Chartist.extend({}, baseOptions);
if (responsiveOptions) {
for (i = 0; i < responsiveOptions.length; i++) {
var mql = window.matchMedia(responsiveOptions[i][0]);
if (mql.matches) {
currentOptions = Chartist.extend(currentOptions, responsiveOptions[i][1]);
}
}
}
if(eventEmitter) {
eventEmitter.emit('optionsChanged', {
previousOptions: previousOptions,
currentOptions: currentOptions
});
}
}
function removeMediaQueryListeners() {
mediaQueryListeners.forEach(function(mql) {
mql.removeListener(updateCurrentOptions);
});
}
if (!window.matchMedia) {
throw 'window.matchMedia not found! Make sure you\'re using a polyfill.';
} else if (responsiveOptions) {
for (i = 0; i < responsiveOptions.length; i++) {
var mql = window.matchMedia(responsiveOptions[i][0]);
mql.addListener(updateCurrentOptions);
mediaQueryListeners.push(mql);
}
}
// Execute initially so we get the correct options
updateCurrentOptions();
return {
get currentOptions() {
return Chartist.extend({}, currentOptions);
},
removeMediaQueryListeners: removeMediaQueryListeners
};
};
//TODO: For arrays it would be better to take the sequence into account and try to minimize modify deltas
/**
* This method will analyze deltas recursively in two objects. The returned object will contain a __delta__ property
* where deltas for specific object properties can be found for the given object nesting level. For nested objects the
* resulting delta descriptor object will contain properties to reflect the nesting. Nested descriptor objects also
* contain a __delta__ property with the deltas of their level.
*
* @param {Object|Array} a Object that should be used to analyzed delta to object b
* @param {Object|Array} b The second object where the deltas from a should be analyzed
* @returns {Object} Delta descriptor object or null
*/
Chartist.deltaDescriptor = function(a, b) {
var summary = {
added: 0,
removed: 0,
modified: 0
};
function findDeltasRecursively(a, b) {
var descriptor = {
__delta__: {}
};
// First check for removed and modified properties
Object.keys(a).forEach(function(property) {
if(!b.hasOwnProperty(property)) {
descriptor.__delta__[property] = {
type: 'remove',
property: property,
ours: a[property]
};
summary.removed++;
} else {
if(typeof a[property] === 'object') {
var subDescriptor = findDeltasRecursively(a[property], b[property]);
if(subDescriptor) {
descriptor[property] = subDescriptor;
}
} else {
if(a[property] !== b[property]) {
descriptor.__delta__[property] = {
type: 'modify',
property: property,
ours: a[property],
theirs: b[property]
};
summary.modified++;
}
}
}
});
// Check for added properties
Object.keys(b).forEach(function(property) {
if(!a.hasOwnProperty(property)) {
descriptor.__delta__[property] = {
type: 'added',
property: property,
theirs: b[property]
};
summary.added++;
}
});
return (Object.keys(descriptor).length !== 1 || Object.keys(descriptor.__delta__).length > 0) ? descriptor : null;
}
var delta = findDeltasRecursively(a, b);
if(delta) {
delta.__delta__.summary = summary;
}
return delta;
};
//http://schepers.cc/getting-to-the-point
Chartist.catmullRom2bezier = function (crp, z) {
var d = [];
for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
var p = [
{x: +crp[i - 2], y: +crp[i - 1]},
{x: +crp[i], y: +crp[i + 1]},
{x: +crp[i + 2], y: +crp[i + 3]},
{x: +crp[i + 4], y: +crp[i + 5]}
];
if (z) {
if (!i) {
p[0] = {x: +crp[iLen - 2], y: +crp[iLen - 1]};
} else if (iLen - 4 === i) {
p[3] = {x: +crp[0], y: +crp[1]};
} else if (iLen - 2 === i) {
p[2] = {x: +crp[0], y: +crp[1]};
p[3] = {x: +crp[2], y: +crp[3]};
}
} else {
if (iLen - 4 === i) {
p[3] = p[2];
} else if (!i) {
p[0] = {x: +crp[i], y: +crp[i + 1]};
}
}
d.push(
[
(-p[0].x + 6 * p[1].x + p[2].x) / 6,
(-p[0].y + 6 * p[1].y + p[2].y) / 6,
(p[1].x + 6 * p[2].x - p[3].x) / 6,
(p[1].y + 6 * p[2].y - p[3].y) / 6,
p[2].x,
p[2].y
]
);
}
return d;
};
}(window, document, Chartist));
| source/scripts/chartist.core.js | /**
* The core module of Chartist that is mainly providing static functions and higher level functions for chart modules.
*
* @module Chartist.Core
*/
var Chartist = {};
Chartist.version = '0.3.1';
(function (window, document, Chartist) {
'use strict';
/**
* Helps to simplify functional style code
*
* @memberof Chartist.Core
* @param {*} n This exact value will be returned by the noop function
* @return {*} The same value that was provided to the n parameter
*/
Chartist.noop = function (n) {
return n;
};
/**
* Generates a-z from a number 0 to 26
*
* @memberof Chartist.Core
* @param {Number} n A number from 0 to 26 that will result in a letter a-z
* @return {String} A character from a-z based on the input number n
*/
Chartist.alphaNumerate = function (n) {
// Limit to a-z
return String.fromCharCode(97 + n % 26);
};
// TODO: Make it possible to call extend with var args
/**
* Simple recursive object extend
*
* @memberof Chartist.Core
* @param {Object} target Target object where the source will be merged into
* @param {Object} source This object will be merged into target and then target is returned
* @return {Object} An object that has the same reference as target but is extended and merged with the properties of source
*/
Chartist.extend = function (target, source) {
target = target || {};
for (var prop in source) {
if (typeof source[prop] === 'object') {
target[prop] = Chartist.extend(target[prop], source[prop]);
} else {
target[prop] = source[prop];
}
}
return target;
};
/**
* Converts a string to a number while removing the unit px if present. If a number is passed then this will be returned unmodified.
*
* @param {String|Number} length
* @returns {Number} Returns the pixel as number or NaN if the passed length could not be converted to pixel
*/
Chartist.getPixelLength = function(length) {
if(typeof length === 'string') {
length = length.replace(/px/i, '');
}
return +length;
};
/**
* This is a wrapper around document.querySelector that will return the query if it's already of type Node
*
* @memberof Chartist.Core
* @param {String|Node} query The query to use for selecting a Node or a DOM node that will be returned directly
* @return {Node}
*/
Chartist.querySelector = function(query) {
return query instanceof Node ? query : document.querySelector(query);
};
/**
* Create or reinitialize the SVG element for the chart
*
* @memberof Chartist.Core
* @param {Node} container The containing DOM Node object that will be used to plant the SVG element
* @param {String} width Set the width of the SVG element. Default is 100%
* @param {String} height Set the height of the SVG element. Default is 100%
* @param {String} className Specify a class to be added to the SVG element
* @return {Object} The created/reinitialized SVG element
*/
Chartist.createSvg = function (container, width, height, className) {
var svg;
width = width || '100%';
height = height || '100%';
// If already contains our svg object we clear it, set width / height and return
if (container.__chartist__ && container.__chartist__.svg) {
svg = container.__chartist__.svg.attr({
width: width,
height: height
}).removeAllClasses().addClass(className).attr({
style: 'width: ' + width + '; height: ' + height + ';'
});
// Clear the draw if its already used before so we start fresh
svg.empty();
} else {
// Create svg object with width and height or use 100% as default
svg = Chartist.Svg('svg').attr({
width: width,
height: height
}).addClass(className).attr({
style: 'width: ' + width + '; height: ' + height + ';'
});
// Add the DOM node to our container
container.appendChild(svg._node);
}
return svg;
};
/**
* Convert data series into plain array
*
* @memberof Chartist.Core
* @param {Object} data The series object that contains the data to be visualized in the chart
* @return {Array} A plain array that contains the data to be visualized in the chart
*/
Chartist.getDataArray = function (data) {
var array = [];
for (var i = 0; i < data.series.length; i++) {
// If the series array contains an object with a data property we will use the property
// otherwise the value directly (array or number)
array[i] = typeof(data.series[i]) === 'object' && data.series[i].data !== undefined ?
data.series[i].data : data.series[i];
// Convert values to number
for (var j = 0; j < array[i].length; j++) {
array[i][j] = +array[i][j];
}
}
return array;
};
/**
* Adds missing values at the end of the array. This array contains the data, that will be visualized in the chart
*
* @memberof Chartist.Core
* @param {Array} dataArray The array that contains the data to be visualized in the chart. The array in this parameter will be modified by function.
* @param {Number} length The length of the x-axis data array.
* @return {Array} The array that got updated with missing values.
*/
Chartist.normalizeDataArray = function (dataArray, length) {
for (var i = 0; i < dataArray.length; i++) {
if (dataArray[i].length === length) {
continue;
}
for (var j = dataArray[i].length; j < length; j++) {
dataArray[i][j] = 0;
}
}
return dataArray;
};
/**
* Calculate the order of magnitude for the chart scale
*
* @memberof Chartist.Core
* @param {Number} value The value Range of the chart
* @return {Number} The order of magnitude
*/
Chartist.orderOfMagnitude = function (value) {
return Math.floor(Math.log(Math.abs(value)) / Math.LN10);
};
/**
* Project a data length into screen coordinates (pixels)
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Number} length Single data value from a series array
* @param {Object} bounds All the values to set the bounds of the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @return {Number} The projected data length in pixels
*/
Chartist.projectLength = function (svg, length, bounds, options) {
var availableHeight = Chartist.getAvailableHeight(svg, options);
return (length / bounds.range * availableHeight);
};
/**
* Get the height of the area in the chart for the data series
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @return {Number} The height of the area in the chart for the data series
*/
Chartist.getAvailableHeight = function (svg, options) {
return Math.max((Chartist.getPixelLength(options.height) || svg.height()) - (options.chartPadding * 2) - options.axisX.offset, 0);
};
/**
* Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.
*
* @memberof Chartist.Core
* @param {Array} dataArray The array that contains the data to be visualized in the chart
* @return {Array} The array that contains the highest and lowest value that will be visualized on the chart.
*/
Chartist.getHighLow = function (dataArray) {
var i,
j,
highLow = {
high: -Number.MAX_VALUE,
low: Number.MAX_VALUE
};
for (i = 0; i < dataArray.length; i++) {
for (j = 0; j < dataArray[i].length; j++) {
if (dataArray[i][j] > highLow.high) {
highLow.high = dataArray[i][j];
}
if (dataArray[i][j] < highLow.low) {
highLow.low = dataArray[i][j];
}
}
}
return highLow;
};
// Find the highest and lowest values in a two dimensional array and calculate scale based on order of magnitude
/**
* Calculate and retrieve all the bounds for the chart and return them in one array
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Array} normalizedData The array that got updated with missing values.
* @param {Object} options The Object that contains all the optional values for the chart
* @param {Number} referenceValue The reference value for the chart.
* @return {Object} All the values to set the bounds of the chart
*/
Chartist.getBounds = function (svg, normalizedData, options, referenceValue) {
var i,
newMin,
newMax,
bounds = Chartist.getHighLow(normalizedData);
// Overrides of high / low from settings
bounds.high = +options.high || (options.high === 0 ? 0 : bounds.high);
bounds.low = +options.low || (options.low === 0 ? 0 : bounds.low);
// If high and low are the same because of misconfiguration or flat data (only the same value) we need
// to set the high or low to 0 depending on the polarity
if(bounds.high === bounds.low) {
// If both values are 0 we set high to 1
if(bounds.low === 0) {
bounds.high = 1;
} else if(bounds.low < 0) {
// If we have the same negative value for the bounds we set bounds.high to 0
bounds.high = 0;
} else {
// If we have the same positive value for the bounds we set bounds.low to 0
bounds.low = 0;
}
}
// Overrides of high / low based on reference value, it will make sure that the invisible reference value is
// used to generate the chart. This is useful when the chart always needs to contain the position of the
// invisible reference value in the view i.e. for bipolar scales.
if (referenceValue || referenceValue === 0) {
bounds.high = Math.max(referenceValue, bounds.high);
bounds.low = Math.min(referenceValue, bounds.low);
}
bounds.valueRange = bounds.high - bounds.low;
bounds.oom = Chartist.orderOfMagnitude(bounds.valueRange);
bounds.min = Math.floor(bounds.low / Math.pow(10, bounds.oom)) * Math.pow(10, bounds.oom);
bounds.max = Math.ceil(bounds.high / Math.pow(10, bounds.oom)) * Math.pow(10, bounds.oom);
bounds.range = bounds.max - bounds.min;
bounds.step = Math.pow(10, bounds.oom);
bounds.numberOfSteps = Math.round(bounds.range / bounds.step);
// Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace
// If we are already below the scaleMinSpace value we will scale up
var length = Chartist.projectLength(svg, bounds.step, bounds, options),
scaleUp = length < options.axisY.scaleMinSpace;
while (true) {
if (scaleUp && Chartist.projectLength(svg, bounds.step, bounds, options) <= options.axisY.scaleMinSpace) {
bounds.step *= 2;
} else if (!scaleUp && Chartist.projectLength(svg, bounds.step / 2, bounds, options) >= options.axisY.scaleMinSpace) {
bounds.step /= 2;
} else {
break;
}
}
// Narrow min and max based on new step
newMin = bounds.min;
newMax = bounds.max;
for (i = bounds.min; i <= bounds.max; i += bounds.step) {
if (i + bounds.step < bounds.low) {
newMin += bounds.step;
}
if (i - bounds.step > bounds.high) {
newMax -= bounds.step;
}
}
bounds.min = newMin;
bounds.max = newMax;
bounds.range = bounds.max - bounds.min;
bounds.values = [];
for (i = bounds.min; i <= bounds.max; i += bounds.step) {
bounds.values.push(i);
}
return bounds;
};
/**
* Calculate cartesian coordinates of polar coordinates
*
* @memberof Chartist.Core
* @param {Number} centerX X-axis coordinates of center point of circle segment
* @param {Number} centerY X-axis coordinates of center point of circle segment
* @param {Number} radius Radius of circle segment
* @param {Number} angleInDegrees Angle of circle segment in degrees
* @return {Number} Coordinates of point on circumference
*/
Chartist.polarToCartesian = function (centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
};
/**
* Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right
*
* @memberof Chartist.Core
* @param {Object} svg The svg element for the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @return {Object} The chart rectangles coordinates inside the svg element plus the rectangles measurements
*/
Chartist.createChartRect = function (svg, options) {
var yOffset = options.axisY ? options.axisY.offset : 0,
xOffset = options.axisX ? options.axisX.offset : 0;
return {
x1: options.chartPadding + yOffset,
y1: Math.max((Chartist.getPixelLength(options.height) || svg.height()) - options.chartPadding - xOffset, options.chartPadding),
x2: Math.max((Chartist.getPixelLength(options.width) || svg.width()) - options.chartPadding, options.chartPadding + yOffset),
y2: options.chartPadding,
width: function () {
return this.x2 - this.x1;
},
height: function () {
return this.y1 - this.y2;
}
};
};
/**
* Creates a label with text and based on support of SVG1.1 extensibility will use a foreignObject with a SPAN element or a fallback to a regular SVG text element.
*
* @param {Object} parent The SVG element where the label should be created as a child
* @param {String} text The label text
* @param {Object} attributes An object with all attributes that should be set on the label element
* @param {String} className The class names that should be set for this element
* @param {Boolean} supportsForeignObject If this is true then a foreignObject will be used instead of a text element
* @returns {Object} The newly created SVG element
*/
Chartist.createLabel = function(parent, text, attributes, className, supportsForeignObject) {
if(supportsForeignObject) {
var content = '<span class="' + className + '">' + text + '</span>';
return parent.foreignObject(content, attributes);
} else {
return parent.elem('text', attributes, className).text(text);
}
};
/**
* Generate grid lines and labels for the x-axis into grid and labels group SVG elements
*
* @memberof Chartist.Core
* @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element
* @param {Object} data The Object that contains the data to be visualized in the chart
* @param {Object} grid Chartist.Svg wrapper object to be filled with the grid lines of the chart
* @param {Object} labels Chartist.Svg wrapper object to be filled with the lables of the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @param {Object} eventEmitter The passed event emitter will be used to emit draw events for labels and gridlines
* @param {Boolean} supportsForeignObject If this is true then a foreignObject will be used instead of a text element
*/
Chartist.createXAxis = function (chartRect, data, grid, labels, options, eventEmitter, supportsForeignObject) {
// Create X-Axis
data.labels.forEach(function (value, index) {
var interpolatedValue = options.axisX.labelInterpolationFnc(value, index),
width = chartRect.width() / data.labels.length,
height = options.axisX.offset,
pos = chartRect.x1 + width * index;
// If interpolated value returns falsey (except 0) we don't draw the grid line
if (!interpolatedValue && interpolatedValue !== 0) {
return;
}
if (options.axisX.showGrid) {
var gridElement = grid.elem('line', {
x1: pos,
y1: chartRect.y1,
x2: pos,
y2: chartRect.y2
}, [options.classNames.grid, options.classNames.horizontal].join(' '));
// Event for grid draw
eventEmitter.emit('draw', {
type: 'grid',
axis: 'x',
index: index,
group: grid,
element: gridElement,
x1: pos,
y1: chartRect.y1,
x2: pos,
y2: chartRect.y2
});
}
if (options.axisX.showLabel) {
var labelPosition = {
x: pos + options.axisX.labelOffset.x,
y: chartRect.y1 + options.axisX.labelOffset.y + (supportsForeignObject ? 5 : 20)
};
var labelElement = Chartist.createLabel(labels, '' + interpolatedValue, {
x: labelPosition.x,
y: labelPosition.y,
width: width,
height: height,
style: 'overflow: visible;'
}, [options.classNames.label, options.classNames.horizontal].join(' '), supportsForeignObject);
eventEmitter.emit('draw', {
type: 'label',
axis: 'x',
index: index,
group: labels,
element: labelElement,
text: '' + interpolatedValue,
x: labelPosition.x,
y: labelPosition.y,
width: width,
height: height,
// TODO: Remove in next major release
get space() {
window.console.warn('EventEmitter: space is deprecated, use width or height instead.');
return this.width;
}
});
}
});
};
/**
* Generate grid lines and labels for the y-axis into grid and labels group SVG elements
*
* @memberof Chartist.Core
* @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element
* @param {Object} bounds All the values to set the bounds of the chart
* @param {Object} grid Chartist.Svg wrapper object to be filled with the grid lines of the chart
* @param {Object} labels Chartist.Svg wrapper object to be filled with the lables of the chart
* @param {Object} options The Object that contains all the optional values for the chart
* @param {Object} eventEmitter The passed event emitter will be used to emit draw events for labels and gridlines
* @param {Boolean} supportsForeignObject If this is true then a foreignObject will be used instead of a text element
*/
Chartist.createYAxis = function (chartRect, bounds, grid, labels, options, eventEmitter, supportsForeignObject) {
// Create Y-Axis
bounds.values.forEach(function (value, index) {
var interpolatedValue = options.axisY.labelInterpolationFnc(value, index),
width = options.axisY.offset,
height = chartRect.height() / bounds.values.length,
pos = chartRect.y1 - height * index;
// If interpolated value returns falsey (except 0) we don't draw the grid line
if (!interpolatedValue && interpolatedValue !== 0) {
return;
}
if (options.axisY.showGrid) {
var gridElement = grid.elem('line', {
x1: chartRect.x1,
y1: pos,
x2: chartRect.x2,
y2: pos
}, [options.classNames.grid, options.classNames.vertical].join(' '));
// Event for grid draw
eventEmitter.emit('draw', {
type: 'grid',
axis: 'y',
index: index,
group: grid,
element: gridElement,
x1: chartRect.x1,
y1: pos,
x2: chartRect.x2,
y2: pos
});
}
if (options.axisY.showLabel) {
var labelPosition = {
x: options.chartPadding + options.axisY.labelOffset.x + (supportsForeignObject ? -10 : 0),
y: pos + options.axisY.labelOffset.y + (supportsForeignObject ? -15 : 0)
};
var labelElement = Chartist.createLabel(labels, '' + interpolatedValue, {
x: labelPosition.x,
y: labelPosition.y,
width: width,
height: height,
style: 'overflow: visible;'
}, [options.classNames.label, options.classNames.vertical].join(' '), supportsForeignObject);
eventEmitter.emit('draw', {
type: 'label',
axis: 'y',
index: index,
group: labels,
element: labelElement,
text: '' + interpolatedValue,
x: labelPosition.x,
y: labelPosition.y,
width: width,
height: height,
// TODO: Remove in next major release
get space() {
window.console.warn('EventEmitter: space is deprecated, use width or height instead.');
return this.height;
}
});
}
});
};
/**
* Determine the current point on the svg element to draw the data series
*
* @memberof Chartist.Core
* @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element
* @param {Object} bounds All the values to set the bounds of the chart
* @param {Array} data The array that contains the data to be visualized in the chart
* @param {Number} index The index of the current project point
* @return {Object} The coordinates object of the current project point containing an x and y number property
*/
Chartist.projectPoint = function (chartRect, bounds, data, index) {
return {
x: chartRect.x1 + chartRect.width() / data.length * index,
y: chartRect.y1 - chartRect.height() * (data[index] - bounds.min) / (bounds.range + bounds.step)
};
};
// TODO: With multiple media queries the handleMediaChange function is triggered too many times, only need one
/**
* Provides options handling functionality with callback for options changes triggered by responsive options and media query matches
*
* @memberof Chartist.Core
* @param {Object} defaultOptions Default options from Chartist
* @param {Object} options Options set by user
* @param {Array} responsiveOptions Optional functions to add responsive behavior to chart
* @param {Object} eventEmitter The event emitter that will be used to emit the options changed events
* @return {Object} The consolidated options object from the defaults, base and matching responsive options
*/
Chartist.optionsProvider = function (defaultOptions, options, responsiveOptions, eventEmitter) {
var baseOptions = Chartist.extend(Chartist.extend({}, defaultOptions), options),
currentOptions,
mediaQueryListeners = [],
i;
function updateCurrentOptions() {
var previousOptions = currentOptions;
currentOptions = Chartist.extend({}, baseOptions);
if (responsiveOptions) {
for (i = 0; i < responsiveOptions.length; i++) {
var mql = window.matchMedia(responsiveOptions[i][0]);
if (mql.matches) {
currentOptions = Chartist.extend(currentOptions, responsiveOptions[i][1]);
}
}
}
if(eventEmitter) {
eventEmitter.emit('optionsChanged', {
previousOptions: previousOptions,
currentOptions: currentOptions
});
}
}
function removeMediaQueryListeners() {
mediaQueryListeners.forEach(function(mql) {
mql.removeListener(updateCurrentOptions);
});
}
if (!window.matchMedia) {
throw 'window.matchMedia not found! Make sure you\'re using a polyfill.';
} else if (responsiveOptions) {
for (i = 0; i < responsiveOptions.length; i++) {
var mql = window.matchMedia(responsiveOptions[i][0]);
mql.addListener(updateCurrentOptions);
mediaQueryListeners.push(mql);
}
}
// Execute initially so we get the correct options
updateCurrentOptions();
return {
get currentOptions() {
return Chartist.extend({}, currentOptions);
},
removeMediaQueryListeners: removeMediaQueryListeners
};
};
//http://schepers.cc/getting-to-the-point
Chartist.catmullRom2bezier = function (crp, z) {
var d = [];
for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
var p = [
{x: +crp[i - 2], y: +crp[i - 1]},
{x: +crp[i], y: +crp[i + 1]},
{x: +crp[i + 2], y: +crp[i + 3]},
{x: +crp[i + 4], y: +crp[i + 5]}
];
if (z) {
if (!i) {
p[0] = {x: +crp[iLen - 2], y: +crp[iLen - 1]};
} else if (iLen - 4 === i) {
p[3] = {x: +crp[0], y: +crp[1]};
} else if (iLen - 2 === i) {
p[2] = {x: +crp[0], y: +crp[1]};
p[3] = {x: +crp[2], y: +crp[3]};
}
} else {
if (iLen - 4 === i) {
p[3] = p[2];
} else if (!i) {
p[0] = {x: +crp[i], y: +crp[i + 1]};
}
}
d.push(
[
(-p[0].x + 6 * p[1].x + p[2].x) / 6,
(-p[0].y + 6 * p[1].y + p[2].y) / 6,
(p[1].x + 6 * p[2].x - p[3].x) / 6,
(p[1].y + 6 * p[2].y - p[3].y) / 6,
p[2].x,
p[2].y
]
);
}
return d;
};
}(window, document, Chartist));
| Added delta analysis method in core for later use in progressive data updates
| source/scripts/chartist.core.js | Added delta analysis method in core for later use in progressive data updates | <ide><path>ource/scripts/chartist.core.js
<ide> },
<ide> removeMediaQueryListeners: removeMediaQueryListeners
<ide> };
<add> };
<add>
<add> //TODO: For arrays it would be better to take the sequence into account and try to minimize modify deltas
<add> /**
<add> * This method will analyze deltas recursively in two objects. The returned object will contain a __delta__ property
<add> * where deltas for specific object properties can be found for the given object nesting level. For nested objects the
<add> * resulting delta descriptor object will contain properties to reflect the nesting. Nested descriptor objects also
<add> * contain a __delta__ property with the deltas of their level.
<add> *
<add> * @param {Object|Array} a Object that should be used to analyzed delta to object b
<add> * @param {Object|Array} b The second object where the deltas from a should be analyzed
<add> * @returns {Object} Delta descriptor object or null
<add> */
<add> Chartist.deltaDescriptor = function(a, b) {
<add> var summary = {
<add> added: 0,
<add> removed: 0,
<add> modified: 0
<add> };
<add>
<add> function findDeltasRecursively(a, b) {
<add> var descriptor = {
<add> __delta__: {}
<add> };
<add>
<add> // First check for removed and modified properties
<add> Object.keys(a).forEach(function(property) {
<add> if(!b.hasOwnProperty(property)) {
<add> descriptor.__delta__[property] = {
<add> type: 'remove',
<add> property: property,
<add> ours: a[property]
<add> };
<add> summary.removed++;
<add> } else {
<add> if(typeof a[property] === 'object') {
<add> var subDescriptor = findDeltasRecursively(a[property], b[property]);
<add> if(subDescriptor) {
<add> descriptor[property] = subDescriptor;
<add> }
<add> } else {
<add> if(a[property] !== b[property]) {
<add> descriptor.__delta__[property] = {
<add> type: 'modify',
<add> property: property,
<add> ours: a[property],
<add> theirs: b[property]
<add> };
<add> summary.modified++;
<add> }
<add> }
<add> }
<add> });
<add>
<add> // Check for added properties
<add> Object.keys(b).forEach(function(property) {
<add> if(!a.hasOwnProperty(property)) {
<add> descriptor.__delta__[property] = {
<add> type: 'added',
<add> property: property,
<add> theirs: b[property]
<add> };
<add> summary.added++;
<add> }
<add> });
<add>
<add> return (Object.keys(descriptor).length !== 1 || Object.keys(descriptor.__delta__).length > 0) ? descriptor : null;
<add> }
<add>
<add> var delta = findDeltasRecursively(a, b);
<add> if(delta) {
<add> delta.__delta__.summary = summary;
<add> }
<add>
<add> return delta;
<ide> };
<ide>
<ide> //http://schepers.cc/getting-to-the-point |
|
Java | apache-2.0 | 71844bcd34377d12635372a5ec5f2c97f2862d39 | 0 | ottlinger/fotorenamer,ottlinger/fotorenamer,ottlinger/fotorenamer | /*
Copyright 2011, Aiki IT, FotoRenamer
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.aikiit.fotorenamer.exception;
import org.apache.log4j.Logger;
import java.io.File;
/**
* Exception that indicates that an error occurred when touching the selected
* directory.
*
* @author hirsch
* @version 04.03.11
*/
public class InvalidDirectoryException extends Exception {
/**
* Logger.
*/
private static final Logger LOG =
Logger.getLogger(InvalidDirectoryException.class);
/**
* Shows and logs a given error message.
* @param message the error message.
*/
public InvalidDirectoryException(String message) {
super(message);
LOG.error("invalid directory: " + message);
}
/**
* Provide error messages for one directory.
*
* @param directory Current directory.
*/
public InvalidDirectoryException(final File directory) {
super(directory.toString());
LOG.error("invalid directory: " + directory);
}
}
| src/main/java/de/aikiit/fotorenamer/exception/InvalidDirectoryException.java | /*
Copyright 2011, Aiki IT, FotoRenamer
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.aikiit.fotorenamer.exception;
import org.apache.log4j.Logger;
import java.io.File;
/**
* Exception that indicates that an error occurred when touching the selected
* directory.
*
* @author hirsch
* @version 04.03.11
*/
public class InvalidDirectoryException extends Exception {
/**
* Logger.
*/
private static final Logger LOG =
Logger.getLogger(InvalidDirectoryException.class);
public InvalidDirectoryException(String message) {
super(message);
LOG.error("invalid directory: " + message);
}
/**
* Provide error messages for one directory.
*
* @param directory Current directory.
*/
public InvalidDirectoryException(final File directory) {
super(directory.toString());
LOG.error("invalid directory: " + directory);
}
}
| Fix javadoc
| src/main/java/de/aikiit/fotorenamer/exception/InvalidDirectoryException.java | Fix javadoc | <ide><path>rc/main/java/de/aikiit/fotorenamer/exception/InvalidDirectoryException.java
<ide> private static final Logger LOG =
<ide> Logger.getLogger(InvalidDirectoryException.class);
<ide>
<add> /**
<add> * Shows and logs a given error message.
<add> * @param message the error message.
<add> */
<ide> public InvalidDirectoryException(String message) {
<ide> super(message);
<ide> LOG.error("invalid directory: " + message); |
|
JavaScript | mit | e4afdb99920bdd40620038a0985ed0f35d6a15b6 | 0 | scriptit/octo-release | import test from 'testit';
import octoRelease from '../src';
if (process.env.TRAVIS_TAG) {
console.log('Refusing to build a tag');
process.exit(0);
}
test('upload a new release', () => {
const time = (new Date()).toISOString();
console.log(time);
return octoRelease(process.env.GITHUB_TOKEN, 'scriptit', 'octo-release', {
tag: time.replace(/\:/g, ''),
name: time,
prerelease: true,
files: [{name: 'file-1.txt', path: __dirname + '/assets/file-1.txt'}],
folders: [{name: 'assets', path: __dirname + '/assets/'}],
});
});
| test/index.js | import test from 'testit';
import octoRelease from '../src';
test('upload a new release', () => {
const time = (new Date()).toISOString();
console.log(time);
return octoRelease(process.env.GITHUB_TOKEN, 'scriptit', 'octo-release', {
tag: time.replace(/\:/g, ''),
name: time,
prerelease: true,
files: [{name: 'file-1.txt', path: __dirname + '/assets/file-1.txt'}],
folders: [{name: 'assets', path: __dirname + '/assets/'}],
});
});
| Prevent infinite cycle of builds
| test/index.js | Prevent infinite cycle of builds | <ide><path>est/index.js
<ide> import test from 'testit';
<ide> import octoRelease from '../src';
<ide>
<add>if (process.env.TRAVIS_TAG) {
<add> console.log('Refusing to build a tag');
<add> process.exit(0);
<add>}
<ide> test('upload a new release', () => {
<ide> const time = (new Date()).toISOString();
<ide> console.log(time); |
|
Java | apache-2.0 | 39193e996e5d9555c11cf33ab849adf7d7620b89 | 0 | francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.replication.regionserver;
import static org.junit.Assert.assertEquals;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.regionserver.wal.HLog;
import org.apache.hadoop.hbase.regionserver.wal.HLogFactory;
import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.replication.ReplicationSourceDummy;
import org.apache.hadoop.hbase.replication.ReplicationZookeeper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(MediumTests.class)
public class TestReplicationSourceManager {
private static final Log LOG =
LogFactory.getLog(TestReplicationSourceManager.class);
private static Configuration conf;
private static HBaseTestingUtility utility;
private static Replication replication;
private static ReplicationSourceManager manager;
private static ZooKeeperWatcher zkw;
private static HTableDescriptor htd;
private static HRegionInfo hri;
private static final byte[] r1 = Bytes.toBytes("r1");
private static final byte[] r2 = Bytes.toBytes("r2");
private static final byte[] f1 = Bytes.toBytes("f1");
private static final byte[] test = Bytes.toBytes("test");
private static final String slaveId = "1";
private static FileSystem fs;
private static String logName;
private static Path oldLogDir;
private static Path logDir;
private static CountDownLatch latch;
private static List<String> files = new ArrayList<String>();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
conf = HBaseConfiguration.create();
conf.set("replication.replicationsource.implementation",
ReplicationSourceDummy.class.getCanonicalName());
conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, true);
utility = new HBaseTestingUtility(conf);
utility.startMiniZKCluster();
zkw = new ZooKeeperWatcher(conf, "test", null);
ZKUtil.createWithParents(zkw, "/hbase/replication");
ZKUtil.createWithParents(zkw, "/hbase/replication/peers/1");
ZKUtil.setData(zkw, "/hbase/replication/peers/1",
Bytes.toBytes(conf.get(HConstants.ZOOKEEPER_QUORUM) + ":"
+ conf.get(HConstants.ZOOKEEPER_CLIENT_PORT) + ":/1"));
ZKUtil.createWithParents(zkw, "/hbase/replication/peers/1/peer-state");
ZKUtil.setData(zkw, "/hbase/replication/peers/1/peer-state",
ReplicationZookeeper.ENABLED_ZNODE_BYTES);
ZKUtil.createWithParents(zkw, "/hbase/replication/state");
ZKUtil.setData(zkw, "/hbase/replication/state", ReplicationZookeeper.ENABLED_ZNODE_BYTES);
replication = new Replication(new DummyServer(), fs, logDir, oldLogDir);
manager = replication.getReplicationManager();
fs = FileSystem.get(conf);
oldLogDir = new Path(utility.getDataTestDir(),
HConstants.HREGION_OLDLOGDIR_NAME);
logDir = new Path(utility.getDataTestDir(),
HConstants.HREGION_LOGDIR_NAME);
logName = HConstants.HREGION_LOGDIR_NAME;
manager.addSource(slaveId);
htd = new HTableDescriptor(test);
HColumnDescriptor col = new HColumnDescriptor("f1");
col.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
htd.addFamily(col);
col = new HColumnDescriptor("f2");
col.setScope(HConstants.REPLICATION_SCOPE_LOCAL);
htd.addFamily(col);
hri = new HRegionInfo(htd.getName(), r1, r2);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
manager.join();
utility.shutdownMiniCluster();
}
@Before
public void setUp() throws Exception {
fs.delete(logDir, true);
fs.delete(oldLogDir, true);
}
@After
public void tearDown() throws Exception {
setUp();
}
@Test
public void testLogRoll() throws Exception {
long seq = 0;
long baseline = 1000;
long time = baseline;
KeyValue kv = new KeyValue(r1, f1, r1);
WALEdit edit = new WALEdit();
edit.add(kv);
List<WALActionsListener> listeners = new ArrayList<WALActionsListener>();
listeners.add(replication);
HLog hlog = HLogFactory.createHLog(fs, utility.getDataTestDir(), logName,
conf, listeners, URLEncoder.encode("regionserver:60020", "UTF8"));
manager.init();
HTableDescriptor htd = new HTableDescriptor();
htd.addFamily(new HColumnDescriptor(f1));
// Testing normal log rolling every 20
for(long i = 1; i < 101; i++) {
if(i > 1 && i % 20 == 0) {
hlog.rollWriter();
}
LOG.info(i);
HLogKey key = new HLogKey(hri.getRegionName(), test, seq++,
System.currentTimeMillis(), HConstants.DEFAULT_CLUSTER_ID);
hlog.append(hri, key, edit, htd, true);
}
// Simulate a rapid insert that's followed
// by a report that's still not totally complete (missing last one)
LOG.info(baseline + " and " + time);
baseline += 101;
time = baseline;
LOG.info(baseline + " and " + time);
for (int i = 0; i < 3; i++) {
HLogKey key = new HLogKey(hri.getRegionName(), test, seq++,
System.currentTimeMillis(), HConstants.DEFAULT_CLUSTER_ID);
hlog.append(hri, key, edit, htd, true);
}
assertEquals(6, manager.getHLogs().get(slaveId).size());
hlog.rollWriter();
manager.logPositionAndCleanOldLogs(manager.getSources().get(0).getCurrentPath(),
"1", 0, false, false);
HLogKey key = new HLogKey(hri.getRegionName(), test, seq++,
System.currentTimeMillis(), HConstants.DEFAULT_CLUSTER_ID);
hlog.append(hri, key, edit, htd, true);
assertEquals(1, manager.getHLogs().size());
// TODO Need a case with only 2 HLogs and we only want to delete the first one
}
@Test
public void testNodeFailoverWorkerCopyQueuesFromRSUsingMulti() throws Exception {
LOG.debug("testNodeFailoverWorkerCopyQueuesFromRSUsingMulti");
conf.setBoolean(HConstants.ZOOKEEPER_USEMULTI, true);
final Server server = new DummyServer("hostname0.example.org");
AtomicBoolean replicating = new AtomicBoolean(true);
ReplicationZookeeper rz = new ReplicationZookeeper(server, replicating);
// populate some znodes in the peer znode
files.add("log1");
files.add("log2");
for (String file : files) {
rz.addLogToList(file, "1");
}
// create 3 DummyServers
Server s1 = new DummyServer("dummyserver1.example.org");
Server s2 = new DummyServer("dummyserver2.example.org");
Server s3 = new DummyServer("dummyserver3.example.org");
// create 3 DummyNodeFailoverWorkers
DummyNodeFailoverWorker w1 = new DummyNodeFailoverWorker(
server.getServerName().getServerName(), s1);
DummyNodeFailoverWorker w2 = new DummyNodeFailoverWorker(
server.getServerName().getServerName(), s2);
DummyNodeFailoverWorker w3 = new DummyNodeFailoverWorker(
server.getServerName().getServerName(), s3);
latch = new CountDownLatch(3);
// start the threads
w1.start();
w2.start();
w3.start();
// make sure only one is successful
int populatedMap = 0;
// wait for result now... till all the workers are done.
latch.await();
populatedMap += w1.isLogZnodesMapPopulated() + w2.isLogZnodesMapPopulated()
+ w3.isLogZnodesMapPopulated();
assertEquals(1, populatedMap);
// close out the resources.
rz.close();
server.abort("", null);
}
static class DummyNodeFailoverWorker extends Thread {
private SortedMap<String, SortedSet<String>> logZnodesMap;
Server server;
private String deadRsZnode;
ReplicationZookeeper rz;
public DummyNodeFailoverWorker(String znode, Server s) throws Exception {
this.deadRsZnode = znode;
this.server = s;
rz = new ReplicationZookeeper(server, new AtomicBoolean(true));
}
@Override
public void run() {
try {
logZnodesMap = rz.copyQueuesFromRSUsingMulti(deadRsZnode);
rz.close();
server.abort("Done with testing", null);
} catch (Exception e) {
LOG.error("Got exception while running NodeFailoverWorker", e);
} finally {
latch.countDown();
}
}
/**
* @return 1 when the map is not empty.
*/
private int isLogZnodesMapPopulated() {
Collection<SortedSet<String>> sets = logZnodesMap.values();
if (sets.size() > 1) {
throw new RuntimeException("unexpected size of logZnodesMap: " + sets.size());
}
if (sets.size() == 1) {
SortedSet<String> s = sets.iterator().next();
for (String file : files) {
// at least one file was missing
if (!s.contains(file)) {
return 0;
}
}
return 1; // we found all the files
}
return 0;
}
}
static class DummyServer implements Server {
String hostname;
DummyServer() {
hostname = "hostname.example.org";
}
DummyServer(String hostname) {
this.hostname = hostname;
}
@Override
public Configuration getConfiguration() {
return conf;
}
@Override
public ZooKeeperWatcher getZooKeeper() {
return zkw;
}
@Override
public CatalogTracker getCatalogTracker() {
return null; // To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ServerName getServerName() {
return new ServerName(hostname, 1234, -1L);
}
@Override
public void abort(String why, Throwable e) {
// To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isAborted() {
return false;
}
@Override
public void stop(String why) {
// To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isStopped() {
return false; // To change body of implemented methods use File | Settings | File Templates.
}
}
}
| hbase-server/src/test/java/org/apache/hadoop/hbase/replication/regionserver/TestReplicationSourceManager.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.replication.regionserver;
import static org.junit.Assert.assertEquals;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.regionserver.wal.HLog;
import org.apache.hadoop.hbase.regionserver.wal.HLogFactory;
import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.replication.ReplicationSourceDummy;
import org.apache.hadoop.hbase.replication.ReplicationZookeeper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(MediumTests.class)
public class TestReplicationSourceManager {
private static final Log LOG =
LogFactory.getLog(TestReplicationSourceManager.class);
private static Configuration conf;
private static HBaseTestingUtility utility;
private static Replication replication;
private static ReplicationSourceManager manager;
private static ZooKeeperWatcher zkw;
private static HTableDescriptor htd;
private static HRegionInfo hri;
private static final byte[] r1 = Bytes.toBytes("r1");
private static final byte[] r2 = Bytes.toBytes("r2");
private static final byte[] f1 = Bytes.toBytes("f1");
private static final byte[] test = Bytes.toBytes("test");
private static final String slaveId = "1";
private static FileSystem fs;
private static String logName;
private static Path oldLogDir;
private static Path logDir;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
conf = HBaseConfiguration.create();
conf.set("replication.replicationsource.implementation",
ReplicationSourceDummy.class.getCanonicalName());
conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, true);
utility = new HBaseTestingUtility(conf);
utility.startMiniZKCluster();
zkw = new ZooKeeperWatcher(conf, "test", null);
ZKUtil.createWithParents(zkw, "/hbase/replication");
ZKUtil.createWithParents(zkw, "/hbase/replication/peers/1");
ZKUtil.setData(zkw, "/hbase/replication/peers/1",
Bytes.toBytes(conf.get(HConstants.ZOOKEEPER_QUORUM) + ":"
+ conf.get(HConstants.ZOOKEEPER_CLIENT_PORT) + ":/1"));
ZKUtil.createWithParents(zkw, "/hbase/replication/peers/1/peer-state");
ZKUtil.setData(zkw, "/hbase/replication/peers/1/peer-state",
ReplicationZookeeper.ENABLED_ZNODE_BYTES);
ZKUtil.createWithParents(zkw, "/hbase/replication/state");
ZKUtil.setData(zkw, "/hbase/replication/state", ReplicationZookeeper.ENABLED_ZNODE_BYTES);
replication = new Replication(new DummyServer(), fs, logDir, oldLogDir);
manager = replication.getReplicationManager();
fs = FileSystem.get(conf);
oldLogDir = new Path(utility.getDataTestDir(),
HConstants.HREGION_OLDLOGDIR_NAME);
logDir = new Path(utility.getDataTestDir(),
HConstants.HREGION_LOGDIR_NAME);
logName = HConstants.HREGION_LOGDIR_NAME;
manager.addSource(slaveId);
htd = new HTableDescriptor(test);
HColumnDescriptor col = new HColumnDescriptor("f1");
col.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
htd.addFamily(col);
col = new HColumnDescriptor("f2");
col.setScope(HConstants.REPLICATION_SCOPE_LOCAL);
htd.addFamily(col);
hri = new HRegionInfo(htd.getName(), r1, r2);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
manager.join();
utility.shutdownMiniCluster();
}
@Before
public void setUp() throws Exception {
fs.delete(logDir, true);
fs.delete(oldLogDir, true);
}
@After
public void tearDown() throws Exception {
setUp();
}
@Test
public void testLogRoll() throws Exception {
long seq = 0;
long baseline = 1000;
long time = baseline;
KeyValue kv = new KeyValue(r1, f1, r1);
WALEdit edit = new WALEdit();
edit.add(kv);
List<WALActionsListener> listeners = new ArrayList<WALActionsListener>();
listeners.add(replication);
HLog hlog = HLogFactory.createHLog(fs, utility.getDataTestDir(), logName,
conf, listeners, URLEncoder.encode("regionserver:60020", "UTF8"));
manager.init();
HTableDescriptor htd = new HTableDescriptor();
htd.addFamily(new HColumnDescriptor(f1));
// Testing normal log rolling every 20
for(long i = 1; i < 101; i++) {
if(i > 1 && i % 20 == 0) {
hlog.rollWriter();
}
LOG.info(i);
HLogKey key = new HLogKey(hri.getRegionName(), test, seq++,
System.currentTimeMillis(), HConstants.DEFAULT_CLUSTER_ID);
hlog.append(hri, key, edit, htd, true);
}
// Simulate a rapid insert that's followed
// by a report that's still not totally complete (missing last one)
LOG.info(baseline + " and " + time);
baseline += 101;
time = baseline;
LOG.info(baseline + " and " + time);
for (int i = 0; i < 3; i++) {
HLogKey key = new HLogKey(hri.getRegionName(), test, seq++,
System.currentTimeMillis(), HConstants.DEFAULT_CLUSTER_ID);
hlog.append(hri, key, edit, htd, true);
}
assertEquals(6, manager.getHLogs().get(slaveId).size());
hlog.rollWriter();
manager.logPositionAndCleanOldLogs(manager.getSources().get(0).getCurrentPath(),
"1", 0, false, false);
HLogKey key = new HLogKey(hri.getRegionName(), test, seq++,
System.currentTimeMillis(), HConstants.DEFAULT_CLUSTER_ID);
hlog.append(hri, key, edit, htd, true);
assertEquals(1, manager.getHLogs().size());
// TODO Need a case with only 2 HLogs and we only want to delete the first one
}
static class DummyServer implements Server {
@Override
public Configuration getConfiguration() {
return conf;
}
@Override
public ZooKeeperWatcher getZooKeeper() {
return zkw;
}
@Override
public CatalogTracker getCatalogTracker() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ServerName getServerName() {
return new ServerName("hostname.example.org", 1234, -1L);
}
@Override
public void abort(String why, Throwable e) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isAborted() {
return false;
}
@Override
public void stop(String why) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isStopped() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
}
}
| HBASE-8106 Test to check replication log znodes move is done correctly (Himanshu)
git-svn-id: 949c06ec81f1cb709fd2be51dd530a930344d7b3@1457216 13f79535-47bb-0310-9956-ffa450edef68
| hbase-server/src/test/java/org/apache/hadoop/hbase/replication/regionserver/TestReplicationSourceManager.java | HBASE-8106 Test to check replication log znodes move is done correctly (Himanshu) | <ide><path>base-server/src/test/java/org/apache/hadoop/hbase/replication/regionserver/TestReplicationSourceManager.java
<ide>
<ide> import java.net.URLEncoder;
<ide> import java.util.ArrayList;
<add>import java.util.Collection;
<ide> import java.util.List;
<add>import java.util.SortedMap;
<add>import java.util.SortedSet;
<add>import java.util.concurrent.CountDownLatch;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide> private static Path oldLogDir;
<ide>
<ide> private static Path logDir;
<del>
<add>
<add> private static CountDownLatch latch;
<add>
<add> private static List<String> files = new ArrayList<String>();
<ide>
<ide> @BeforeClass
<ide> public static void setUpBeforeClass() throws Exception {
<ide>
<ide> // TODO Need a case with only 2 HLogs and we only want to delete the first one
<ide> }
<del>
<add>
<add> @Test
<add> public void testNodeFailoverWorkerCopyQueuesFromRSUsingMulti() throws Exception {
<add> LOG.debug("testNodeFailoverWorkerCopyQueuesFromRSUsingMulti");
<add> conf.setBoolean(HConstants.ZOOKEEPER_USEMULTI, true);
<add> final Server server = new DummyServer("hostname0.example.org");
<add> AtomicBoolean replicating = new AtomicBoolean(true);
<add> ReplicationZookeeper rz = new ReplicationZookeeper(server, replicating);
<add> // populate some znodes in the peer znode
<add> files.add("log1");
<add> files.add("log2");
<add> for (String file : files) {
<add> rz.addLogToList(file, "1");
<add> }
<add> // create 3 DummyServers
<add> Server s1 = new DummyServer("dummyserver1.example.org");
<add> Server s2 = new DummyServer("dummyserver2.example.org");
<add> Server s3 = new DummyServer("dummyserver3.example.org");
<add>
<add> // create 3 DummyNodeFailoverWorkers
<add> DummyNodeFailoverWorker w1 = new DummyNodeFailoverWorker(
<add> server.getServerName().getServerName(), s1);
<add> DummyNodeFailoverWorker w2 = new DummyNodeFailoverWorker(
<add> server.getServerName().getServerName(), s2);
<add> DummyNodeFailoverWorker w3 = new DummyNodeFailoverWorker(
<add> server.getServerName().getServerName(), s3);
<add>
<add> latch = new CountDownLatch(3);
<add> // start the threads
<add> w1.start();
<add> w2.start();
<add> w3.start();
<add> // make sure only one is successful
<add> int populatedMap = 0;
<add> // wait for result now... till all the workers are done.
<add> latch.await();
<add> populatedMap += w1.isLogZnodesMapPopulated() + w2.isLogZnodesMapPopulated()
<add> + w3.isLogZnodesMapPopulated();
<add> assertEquals(1, populatedMap);
<add> // close out the resources.
<add> rz.close();
<add> server.abort("", null);
<add> }
<add>
<add> static class DummyNodeFailoverWorker extends Thread {
<add> private SortedMap<String, SortedSet<String>> logZnodesMap;
<add> Server server;
<add> private String deadRsZnode;
<add> ReplicationZookeeper rz;
<add>
<add> public DummyNodeFailoverWorker(String znode, Server s) throws Exception {
<add> this.deadRsZnode = znode;
<add> this.server = s;
<add> rz = new ReplicationZookeeper(server, new AtomicBoolean(true));
<add> }
<add>
<add> @Override
<add> public void run() {
<add> try {
<add> logZnodesMap = rz.copyQueuesFromRSUsingMulti(deadRsZnode);
<add> rz.close();
<add> server.abort("Done with testing", null);
<add> } catch (Exception e) {
<add> LOG.error("Got exception while running NodeFailoverWorker", e);
<add> } finally {
<add> latch.countDown();
<add> }
<add> }
<add>
<add> /**
<add> * @return 1 when the map is not empty.
<add> */
<add> private int isLogZnodesMapPopulated() {
<add> Collection<SortedSet<String>> sets = logZnodesMap.values();
<add> if (sets.size() > 1) {
<add> throw new RuntimeException("unexpected size of logZnodesMap: " + sets.size());
<add> }
<add> if (sets.size() == 1) {
<add> SortedSet<String> s = sets.iterator().next();
<add> for (String file : files) {
<add> // at least one file was missing
<add> if (!s.contains(file)) {
<add> return 0;
<add> }
<add> }
<add> return 1; // we found all the files
<add> }
<add> return 0;
<add> }
<add> }
<add>
<ide> static class DummyServer implements Server {
<add> String hostname;
<add>
<add> DummyServer() {
<add> hostname = "hostname.example.org";
<add> }
<add>
<add> DummyServer(String hostname) {
<add> this.hostname = hostname;
<add> }
<ide>
<ide> @Override
<ide> public Configuration getConfiguration() {
<ide>
<ide> @Override
<ide> public CatalogTracker getCatalogTracker() {
<del> return null; //To change body of implemented methods use File | Settings | File Templates.
<add> return null; // To change body of implemented methods use File | Settings | File Templates.
<ide> }
<ide>
<ide> @Override
<ide> public ServerName getServerName() {
<del> return new ServerName("hostname.example.org", 1234, -1L);
<add> return new ServerName(hostname, 1234, -1L);
<ide> }
<ide>
<ide> @Override
<ide> public void abort(String why, Throwable e) {
<del> //To change body of implemented methods use File | Settings | File Templates.
<del> }
<del>
<add> // To change body of implemented methods use File | Settings | File Templates.
<add> }
<add>
<ide> @Override
<ide> public boolean isAborted() {
<ide> return false;
<ide>
<ide> @Override
<ide> public void stop(String why) {
<del> //To change body of implemented methods use File | Settings | File Templates.
<add> // To change body of implemented methods use File | Settings | File Templates.
<ide> }
<ide>
<ide> @Override
<ide> public boolean isStopped() {
<del> return false; //To change body of implemented methods use File | Settings | File Templates.
<del> }
<del> }
<del>
<add> return false; // To change body of implemented methods use File | Settings | File Templates.
<add> }
<add> }
<ide>
<ide> }
<ide> |
|
JavaScript | mit | 5b42f74e01d1ca8e01e9b1be5db85241f5021425 | 0 | t-yanaka/zabbix-report,olifolkerd/tabulator,t-yanaka/zabbix-report,t-yanaka/zabbix-report,t-yanaka/zabbix-report | /*
* This file is part of the Tabulator package.
*
* (c) Oliver Folkerd <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
(function(){
'use strict';
$.widget("ui.tabulator", {
data:[],//array to hold data for table
activeData:[],//array to hold data that is active in the DOM
firstRender:true, //layout table widths correctly on first render
mouseDrag:false, //mouse drag tracker;
mouseDragWidth:false, //starting width of colum on mouse drag
mouseDragElement:false, //column being dragged
mouseDragOut:false, //catch to prevent mouseup on col drag triggering click on sort
sortCurCol:null,//column name of currently sorted column
sortCurDir:null,//column name of currently sorted column
filterField:null, //field to be filtered on data render
filterValue:null, //value to match on filter
filterType:null, //filter type
paginationCurrentPage:1, // pagination page
paginationMaxPage:1, // pagination maxpage
progressiveRenderTimer:null, //timer for progressiver rendering
loaderDiv: $("<div class='tablulator-loader'><div class='tabulator-loader-msg'></div></div>"), //loader blockout div
//setup options
options: {
colMinWidth:"40px", //minimum global width for a column
colResizable:true, //resizable columns
height:false, //height of tabulator
fitColumns:false, //fit colums to width of screen;
movableCols:false, //enable movable columns
movableRows:false, //enable movable rows
movableRowHandle:"<div></div><div></div><div></div>", //handle for movable rows
columnLayoutCookie:false, //store cookie with column _styles
columnLayoutCookieID:"", //id for stored cookie
pagination:false, //enable pagination
paginationSize:false, //size of pages
paginationAjax:false, //paginate internal or via ajax
paginationElement:false, //element to hold pagination numbers
progressiveRender:false, //enable progressive rendering
progressiveRenderSize:20, //block size for progressive rendering
progressiveRenderMargin:200, //disance in px before end of scroll before progressive render is triggered
tooltips: false, //Tool tip value
columns:[],//store for colum header info
data:false, //store for initial table data if set at construction
index:"id",
sortable:true, //global default for sorting
dateFormat: "dd/mm/yyyy", //date format to be used for sorting
sortBy:"id", //defualt column to sort by
sortDir:"desc", //default sort direction
groupBy:false, //enable table grouping and set field to group by
groupHeader:function(value, count, data){ //header layout function
return value + "<span>(" + count + " item)</span>";
},
rowFormatter:false, //row formatter callback
addRowPos:"bottom", //position to insert blank rows, top|bottom
selectable:true, //highlight rows on hover
ajaxURL:false, //url for ajax loading
ajaxParams:{}, //url for ajax loading
showLoader:true, //show loader while data loading
loader:"<div class='tabulator-loading'>Loading Data</div>", //loader element
loaderError:"<div class='tabulator-error'>Loading Error</div>", //loader element
rowClick:function(){}, //do action on row click
rowAdded:function(){}, //do action on row add
rowEdit:function(){}, //do action on row edit
rowDelete:function(){}, //do action on row delete
rowContext:function(){}, //context menu action
dataLoaded:function(){}, //callback for when data has been Loaded
rowMoved:function(){}, //callback for when row has moved
colMoved:function(){}, //callback for when column has moved
pageLoaded:function(){}, //calback for when a page is loaded
},
////////////////// Element Construction //////////////////
//constructor
_create: function() {
var self = this;
var element = self.element;
if(element.is("table")){
self._parseTable();
}else{
self._buildElement();
}
},
//parse table element to create data set
_parseTable:function(){
var self = this;
var element = self.element;
var options = self.options;
var hasIndex = false;
//build columns from table header if they havnt been set;
if(!options.columns.length){
var headers = $("th", element);
if(headers.length){
//create column array from headers
headers.each(function(index){
var col = {title:$(this).text(), field:$(this).text().toLowerCase().replace(" ", "_")};
var width = $(this).attr("width");
if(width){
col.width = width;
}
if(col.field == options.index){
hasIndex = true;
}
options.columns.push(col);
});
}else{
//create blank table headers
headers = $("tr:first td", element);
headers.each(function(index){
var col = {title:"", field:"col" + index};
var width = $(this).attr("width");
if(width){
col.width = width;
}
options.columns.push(col);
});
}
}
//iterate through table rows and build data set
$("tbody tr", element).each(function(rowIndex){
var item = {};
//create index if the dont exist in table
if(!hasIndex){
item[options.index] = rowIndex;
}
//add row data to item
$("td", $(this)).each(function(colIndex){
item[options.columns[colIndex].field] = $(this).text();
});
self.data.push(item);
});
//create new element
var newElement = $("<div></div>");
//transfer attributes to new element
var attributes = element.prop("attributes");
// loop through attributes and apply them on div
$.each(attributes, function() {
newElement.attr(this.name, this.value);
});
// replace table with div element
element.replaceWith(newElement);
options.data = self.data;
newElement.tabulator(options);
},
//build tabulator element
_buildElement: function() {
var self = this;
var options = self.options;
var element = self.element;
options.colMinWidth = isNaN(options.colMinWidth) ? options.colMinWidth : options.colMinWidth + "px";
if(options.height){
options.height = isNaN(options.height) ? options.height : options.height + "px";
element.css({"height": options.height});
}
if(options.data){
self.data = options.data;
}
element.addClass("tabulator");
self.header = $("<div class='tabulator-header'></div>")
self.tableHolder = $("<div class='tabulator-tableHolder'></div>");
var scrollTop = 0;
var scrollLeft = 0;
self.tableHolder.scroll(function(){
// if(scrollLeft != $(this).scrollLeft()){
self.header.css({"margin-left": "-1" * $(this).scrollLeft()});
// }
//trigger progressive rendering on scroll
if(self.options.progressiveRender && scrollTop != $(this).scrollTop() && scrollTop < $(this).scrollTop()){
if($(this)[0].scrollHeight - $(this).innerHeight() - $(this).scrollTop() < self.options.progressiveRenderMargin){
if(self.paginationCurrentPage < self.paginationMaxPage){
self.paginationCurrentPage++;
self._renderTable(true);
}
}
}
scrollTop = $(this).scrollTop();
});
//create scrollable table holder
self.table = $("<div class='tabulator-table'></div>");
//build pagination footer if needed
if(options.pagination){
if(!options.paginationElement){
options.paginationElement = $("<div class='tabulator-footer'></div>");
self.footer = options.paginationElement;
}
self.paginator = $("<span class='tabulator-paginator'><span class='tabulator-page' data-page='first'>First</span><span class='tabulator-page' data-page='prev'>Prev</span><span class='tabulator-pages'></span><span class='tabulator-page' data-page='next'>Next</span><span class='tabulator-page' data-page='last'>Last</span></span>");
self.paginator.on("click", ".tabulator-page", function(){
if(!$(this).hasClass("disabled")){
self.setPage($(this).data("page"));
}
});
options.paginationElement.append(self.paginator);
}
//layout columns
if(options.columnLayoutCookie){
self._getColCookie();
}else{
self._colLayout();
}
},
//set options
_setOption: function(option, value) {
var self = this;
//block update if option cannot be updated this way
if(["columns"].indexOf(option) > -1){
return false
}
//set option to value
$.Widget.prototype._setOption.apply( this, arguments );
//trigger appropriate table response
if(["colMinWidth", "colResizable", "fitColumns", "movableCols", "movableRows", "movableRowHandle", "sortable", "groupBy", "groupHeader", "rowFormatter", "selectable"].indexOf(option) > -1){
//triger rerender
self._renderTable();
}else if(["height", "pagination", "paginationSize", "tooltips"].indexOf(option) > -1){
//triger render/reset page
if(self.options.pagination){
self.setPage(1);
}else{
self._renderTable();
}
}else if(["dateFormat", "sortBy", "sortDir"].indexOf(option) > -1){
//trigger sort
if(self.sortCurCol){
self.sort(self.sortCurCol, self.sortCurDir);
}
}else if(["index"].indexOf(option) > -1){
//trigger reparse data
self._parseData(self.data);
}else if(["paginationElement"].indexOf(option) > -1){
//trigger complete redraw
}
},
////////////////// General Public Functions //////////////////
//get number of elements in dataset
dataCount:function(){
return this.data.length;
},
//redraw list without updating data
redraw:function(fullRedraw){
var self = this;
//redraw columns
if(self.options.fitColumns){
self._colRender();
}
//reposition loader if present
if(self.element.innerHeight() > 0){
$(".tabulator-loader-msg", self.loaderDiv).css({"margin-top":(self.element.innerHeight() / 2) - ($(".tabulator-loader-msg", self.loaderDiv).outerHeight()/2)})
}
//trigger ro restyle
self._styleRows(true);
if(fullRedraw){
self._renderTable();
}
},
////////////////// Column Manipulation //////////////////
//set column style cookie
_setColCookie:function(){
var self = this;
//set cookie ied
var cookieID = self.options.columnLayoutCookieID ? self.options.columnLayoutCookieID : self.element.attr("id") ? self.element.attr("id") : "";
cookieID = "tabulator-" + cookieID;
//set cookie expiration far in the future
var expDate = new Date();
expDate.setDate(expDate.getDate() + 10000);
//create array of column styles only
var columnStyles = [];
$.each(self.options.columns, function(i, column) {
var style = {
field: column.field,
width: column.width,
visible:column.visible,
};
columnStyles.push(style);
});
//JSON format column data
var data = JSON.stringify(columnStyles);
//save cookie
document.cookie = cookieID + "=" + data + "; expires=" + expDate.toUTCString();
},
//set Column style cookie
_getColCookie:function(){
var self = this;
//set cookie ied
var cookieID = self.options.columnLayoutCookieID ? self.options.columnLayoutCookieID : self.element.attr("id") ? self.element.attr("id") : "";
cookieID = "tabulator-" + cookieID;
//find cookie
var cookie = document.cookie;
var cookiePos = cookie.indexOf(cookieID+"=");
//if cookie exists, decode and load column data into tabulator
if(cookiePos > -1){
cookie = cookie.substr(cookiePos);
var end = cookie.indexOf(";");
if(end > -1){
cookie = cookie.substr(0, end);
}
cookie = cookie.replace(cookieID+"=", "")
self.setColumns(JSON.parse(cookie), true);
}else{
self._colLayout();
}
},
//set tabulator columns
setColumns: function(columns, update){
var self = this;
var oldColumns = self.options.columns;
//if updateing columns work through exisiting column data
if(update){
var newColumns = [];
//iterate through each of the new columns
$.each(columns, function(i, column) {
//find a match in the original column array
var find = column.field;
//var find = column.field == "" ? column : column.field;
$.each(self.options.columns, function(i, origColumn) {
var match = typeof(find) == "object" ? origColumn == find : origColumn.field == find;
//if matching, update layout data and add to new column array
if(match){
var result = self.options.columns.splice(i, 1)[0];
result.width = column.width;
result.visible = column.visible;
newColumns.push(result);
return false;
}
});
});
//if any aditional columns left add them to the end of the table
if(self.options.columns.length > 0){
newColumns.concat(self.options.columns);
}
//replace old columns with new
self.options.columns = newColumns;
//Trigger Redraw
self._colLayout();
}else{
// if replaceing columns, replace columns array with new
self.options.columns = columns;
//Trigger Redraw
self._colLayout();
}
},
//get tabulator columns
getColumns: function(){
var self = this;
return self.options.columns;
},
//find column
_findColumn:function(field){
var self = this;
var result = false
$.each(self.options.columns, function(i, column) {
if(typeof(field) == "object"){
if(column == field){
result = column;
return false;
}
}else{
if(column.field == field){
result = column;
return false;
}
}
});
return result;
},
//hide column
hideCol: function(field){
var self = this;
var column = false;
$.each(self.options.columns, function(i, item) {
if(item.field == field){
column = i;
return false;
}
});
if(column === false){
return false;
}else{
self.options.columns[column].visible = false;
$(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).hide();
self._renderTable();
if(self.options.columnLayoutCookie){
self._setColCookie();
}
return true;
}
},
//show column
showCol: function(field){
var self = this;
var column = false;
$.each(self.options.columns, function(i, item) {
if(item.field == field){
column = i;
return false;
}
});
if(column === false){
return false;
}else{
self.options.columns[column].visible = true;
$(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).show();
self._renderTable();
if(self.options.columnLayoutCookie){
self._setColCookie();
}
return true;
}
},
//toggle column visibility
toggleCol: function(field){
var self = this;
var column = false;
$.each(self.options.columns, function(i, item) {
if(item.field == field){
column = i;
return false;
}
});
if(column === false){
return false;
}else{
self.options.columns[column].visible = !self.options.columns[column].visible;
if(self.options.columns[column].visible){
$(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).show();
}else{
$(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).hide();
}
if(self.options.columnLayoutCookie){
self._setColCookie();
}
self._renderTable();
return true;
}
},
////////////////// Row Manipulation //////////////////
//delete row from table by id
deleteRow: function(item){
var self = this;
var id = typeof(item) == "number" ? item : item.data("data")[self.options.index]
var row = typeof(item) == "number" ? $("[data-id=" + item + "]", self.element) : item;
var rowData = row.data("data");
rowData.tabulator_delete_row = true;
//remove from data
var line = self.data.find(function(rowData){
return item.tabulator_delete_row;
});
if(line){
line = self.data.indexOf(line);
if(line > -1){
//remove row from data
self.data.splice(line, 1);
}
}
//remove from active data
line = self.activeData.find(function(item){
return item.tabulator_delete_row;
});
if(line){
line = self.activeData.indexOf(line);
if(line > -1){
//remove row from data
self.activeData.splice(line, 1);
}
}
var group = row.closest(".tabulator-group");
row.remove();
if(self.options.groupBy){
var length = $(".tabulator-row", group).length;
if(length){
var data = [];
$(".tabulator-row", group).each(function(){
data.push($(this).data("data"));
});
var header = $(".tabulator-group-header", group)
var arrow = $(".tabulator-arrow", header).clone(true,true);
header.empty()
header.append(arrow).append(self.options.groupHeader(group.data("value"), $(".tabulator-row", group).length, data));
}else{
group.remove();
}
}
//style table rows
self._styleRows();
//align column widths
self._colRender(!self.firstRender);
self._trigger("renderComplete");
self.options.rowDelete(id);
self._trigger("dataEdited");
},
//add blank row to table
addRow:function(item){
var self = this;
if(item){
item[self.options.index] = item[self.options.index]? item[self.options.index]: 0;
}else{
item = {id:0}
}
//add item to
//self.data.push(item);
//create blank row
var row = self._renderRow(item);
//append to top or bottom of table based on preference
if(self.options.addRowPos == "top"){
self.activeData.push(item);
self.table.prepend(row);
}else{
self.activeData.unshift(item);
self.table.append(row);
}
//align column widths
self._colRender(!self.firstRender);
self._trigger("renderComplete");
//style table rows
self._styleRows();
//triger event
self.options.rowAdded(item);
self._trigger("dataEdited");
},
////////////////// Data Manipulation //////////////////
//get array of data from the table
getData:function(){
var self = this;
return self.activeData;
},
//load data
setData:function(data, params){
this._trigger("dataLoading");
params = params ? params : {};
//show loader if needed
this._showLoader(this, this.options.loader)
if(typeof(data) === "string"){
if (data.indexOf("{") == 0 || data.indexOf("[") == 0){
//data is a json encoded string
this._parseData(jQuery.parseJSON(data));
}else{
//assume data is url, make ajax call to url to get data
this._getAjaxData(data, params);
}
}else{
if(data){
//asume data is already an object
this._parseData(data);
}else{
//no data provided, check if ajaxURL is present;
if(this.options.ajaxURL){
this._getAjaxData(this.options.ajaxURL, params);
}else{
//empty data
this._parseData([]);
}
}
}
},
//clear data
clear:function(){
this.table.empty();
this.data = [];
this._filterData();
},
//get json data via ajax
_getAjaxData:function(url, params){
var self = this;
var options = self.options;
$.ajax({
url: url,
type: "GET",
data:params,
async: true,
dataType:'json',
success: function (data) {
self._parseData(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Tablulator ERROR (ajax get): " + xhr.status + " - " + thrownError);
self._trigger("dataLoadError", xhr, thrownError);
self._showLoader(self, self.options.loaderError);
},
});
},
//parse and index data
_parseData:function(data){
var self = this;
var newData = [];
if(data.length){
if(typeof(data[0][self.options.index]) == "undefined"){
self.options.index = "_index";
$.each(data, function(i, item) {
newData[i] = item;
newData[i]["_index"] = i;
});
}else{
$.each(data, function(i, item) {
newData.push(item);
});
}
}
self.data = newData;
self.options.dataLoaded(data);
//filter incomming data
self._filterData();
},
////////////////// Data Filtering //////////////////
//filter data in table
setFilter:function(field, type, value){
var self = this;
self._trigger("filterStarted");
//set filter
if(field){
//set filter
self.filterField = field;
self.filterType = typeof(value) == "undefined" ? "=" : type;
self.filterValue = typeof(value) == "undefined" ? type : value;
}else{
//clear filter
self.filterField = null;
self.filterType = null;
self.filterValue = null;
}
//render table
this._filterData();
},
//clear filter
clearFilter:function(){
var self = this;
self.filterField = null;
self.filterType = null;
self.filterValue = null;
//render table
this._filterData();
},
//get current filter info
getFilter:function(){
var self = this;
if(self.filterField){
var filter = {
"field":self.filterField,
"type":self.filterType,
"value":self.filterValue,
};
return filter;
}else{
return false;
}
},
//filter data set
_filterData:function(){
var self = this;
//filter data set
if(self.filterField ){
self.activeData = self.data.filter(function(row){
return self._filterRow(row);
});
}else{
self.activeData = self.data;
}
//set the max pages available given the filter results
if(self.options.pagination){
self.paginationMaxPage = Math.ceil(self.activeData.length/self.options.paginationSize);
}
//sort or render data
if(self.sortCurCol){
self.sort(self.sortCurCol, self.sortCurDir);
}else{
//determine pagination information / render table
if(self.options.pagination){
self.setPage(1);
}else{
self._renderTable();
}
}
},
//check if row data matches filter
_filterRow:function(row){
var self = this;
// if no filter set display row
if(!self.filterField){
return true;
}else{
if(typeof(self.filterField) == "function"){
return self.filterField(row);
}else{
var value = row[self.filterField];
var term = self.filterValue;
switch(self.filterType){
case "=": //equal to
return value == term ? true : false;
break;
case "<": //less than
return value < term ? true : false;
break;
case "<=": //less than or equal too
return value <= term ? true : false;
break;
case ">": //greater than
return value > term ? true : false;
break;
case ">=": //greater than or equal too
return value >= term ? true : false;
break;
case "!=": //not equal to
return value != term ? true : false;
break;
case "like": //text like
return value.toLowerCase().indexOf(term.toLowerCase()) > -1 ? true : false;
break;
default:
return false;
}
}
}
return false;
},
////////////////// Data Sorting //////////////////
//handle user clicking on column header sort
_sortClick: function(column, element){
var self = this;
if (element.data("sortdir") == "desc"){
element.data("sortdir", "asc");
}else{
element.data("sortdir", "desc");
}
self.sort(column, element.data("sortdir"));
},
// public sorter function
sort: function(sortList, dir){
var self = this;
var header = self.header;
var options = this.options;
if(!Array.isArray(sortList)){
sortList = [{field: sortList, dir:dir}];
}
$.each(sortList, function(i, item) {
//convert colmun name to column object
if(typeof(item.field) == "string"){
$.each(options.columns, function(i, col) {
if(col.field == item.field){
item.field = col;
return false;
}
});
}
//reset all column sorts
$(".tabulator-col[data-sortable=true][data-field!=" + item.field.field + "]", self.header).data("sortdir", "desc");
$(".tabulator-col .tabulator-arrow", self.header).removeClass("asc desc")
var element = $(".tabulator-col[data-field='" + item.field.field + "']", header);
if (dir == "asc"){
$(".tabulator-arrow", element).removeClass("desc").addClass("asc");
}else{
$(".tabulator-arrow", element).removeClass("asc").addClass("desc");
}
self._sorter(item.field, item.dir, sortList, i);
});
self._trigger("sortComplete");
//determine pagination information / render table
if(self.options.pagination){
self.setPage(1);
}else{
self._renderTable();
}
},
//sort table
_sorter: function(column, dir, sortList, i){
var self = this;
var table = self.table;
var options = self.options;
var data = self.data;
self._trigger("sortStarted");
self.sortCurCol = column;
self.sortCurDir = dir;
self._sortElement(table, column, dir, sortList, i);
},
//itterate through nested sorters
_sortElement:function(element, column, dir, sortList, i){
var self = this;
self.activeData = self.activeData.sort(function(a,b){
var result = self._processSorter(a, b, column, dir);
//if results match recurse through previous searchs to be sure
if(result == 0 && i){
for(var j = i-1; j>= 0; j--){
result = self._processSorter(a, b, sortList[j].field, sortList[j].dir);
if(result != 0){
break;
}
}
}
return result;
})
},
//process individual sort functions on active data
_processSorter:function(a, b, column, dir){
var self = this;
//switch elements depending on search direction
var el1 = dir == "asc" ? a : b;
var el2 = dir == "asc" ? b : a;
el1 = el1[column.field];
el2 = el2[column.field];
//workaround to format dates correctly
a = column.sorter == "date" ? self._formatDate(el1) : el1;
b = column.sorter == "date" ? self._formatDate(el2) : el2;
//run sorter
var sorter = typeof(column.sorter) == "undefined" ? "string" : column.sorter;
sorter = typeof(sorter) == "string" ? self.sorters[sorter] : sorter;
return sorter(a, b);
},
////////////////// Data Pagination //////////////////
//get current page number
getPage:function(){
var self = this;
return self.options.pagination ? self.paginationCurrentPage : false;
},
//set current paginated page
setPage:function(page){
var self = this;
if(Number.isInteger(page) && page > 0 && page <= self.paginationMaxPage){
self.paginationCurrentPage = page;
}else{
switch(page){
case "first":
self.paginationCurrentPage = 1;
break;
case "prev":
if(self.paginationCurrentPage > 1){
self.paginationCurrentPage--;
}
break;
case "next":
if(self.paginationCurrentPage < self.paginationMaxPage){
self.paginationCurrentPage++;
}
break;
case "last":
self.paginationCurrentPage = self.paginationMaxPage;
break;
}
}
self._layoutPageSelector();
self._renderTable();
},
//set page size for the table
setPageSize:function(size){
var self = this;
self.options.paginationSize = size;
self._filterData();
},
//create page selector layout for current page
_layoutPageSelector:function(){
var self = this;
var min = 1, max = self.paginationMaxPage;
var pages = $(".tabulator-pages", self.paginator);
pages.empty();
var spacer = $("<span> ... </span>");
if(self.paginationMaxPage > 10){
if(self.paginationCurrentPage <= 4){
max = 5;
}else if(self.paginationCurrentPage > self.paginationMaxPage - 4){
min = self.paginationMaxPage - 4;
pages.append(spacer.clone());
}else{
min = self.paginationCurrentPage - 2;
max = self.paginationCurrentPage + 2;
pages.append(spacer.clone());
}
}
for(var i = min; i <= max; ++i){
var active = i == self.paginationCurrentPage ? "active" : "";
pages.append("<span class='tabulator-page " + active + "' data-page='" + i + "'>" + i + "</span>");
}
if(self.paginationMaxPage > 10){
if(self.paginationCurrentPage <= 4 || self.paginationCurrentPage <= self.paginationMaxPage - 4){
pages.append(spacer.clone());
}
}
$(".tabulator-page", self.paginator).removeClass("disabled");
if(self.paginationCurrentPage == 1){
$(".tabulator-page[data-page=first], .tabulator-page[data-page=prev]", self.paginator).addClass("disabled");
}
if(self.paginationCurrentPage == self.paginationMaxPage){
$(".tabulator-page[data-page=next], .tabulator-page[data-page=last]", self.paginator).addClass("disabled");
}
},
////////////////// Render Data to Table //////////////////
//render active data to table rows
_renderTable:function(progressiveRender){
var self = this;
var options = self.options
this._trigger("renderStarted");
//show loader if needed
self._showLoader(self, self.options.loader)
if(!progressiveRender){
clearTimeout(self.progressiveRenderTimer);
//hide table while building
// self.table.hide();
//clear data from table before loading new
self.table.empty();
}
if(!options.pagination && options.progressiveRender && !progressiveRender){
self.paginationCurrentPage = 1;
self.paginationMaxPage = Math.ceil(self.activeData.length/self.options.progressiveRenderSize);
options.paginationSize = options.progressiveRenderSize;
progressiveRender = true;
}
var renderData = options.pagination || options.progressiveRender ? self.activeData.slice((self.paginationCurrentPage-1) * self.options.paginationSize, ((self.paginationCurrentPage-1) * self.options.paginationSize) + self.options.paginationSize) : self.activeData;
//build rows of table
renderData.forEach( function(item, i) {
var row = self._renderRow(item);
if(options.groupBy){
// if groups in use, render column in group
var groupVal = typeof(options.groupBy) == "function" ? options.groupBy(item) : item[options.groupBy];
var group = $(".tabulator-group[data-value='" + groupVal + "']", self.table);
//if group does not exist, build it
if(group.length == 0){
group = self._renderGroup(groupVal);
self.table.append(group);
}
$(".tabulator-group-body", group).append(row);
}else{
//if not grouping output row to table
self.table.append(row);
}
});
//enable movable rows
if(options.movableRows){
var moveBackground ="";
var moveBorder ="";
//sorter options
var config = {
handle:".tabulator-row-handle",
opacity: 1,
axis: "y",
start: function(event, ui){
moveBorder = ui.item.css("border");
moveBackground = ui.item.css("background-color");
ui.item.css({
"border":"1px solid #000",
"background":"#fff",
});
},
stop: function(event, ui){
ui.item.css({
"border": moveBorder,
"background":moveBackground,
});
},
update: function(event, ui) {
//restyle rows
self._styleRows();
//clear sorter arrows
$(".tabulator-col[data-sortable=true]", self.header).data("sortdir", "desc");
$(".tabulator-col .tabulator-arrow", self.header).removeClass("asc desc")
self.activeData = [];
//update active data to mach rows
$(".tabulator-row", self.table).each(function(){
self.activeData.push($(this).data("data"));
});
//trigger callback
options.rowMoved(ui.item.data("id"), ui.item.data("data"), ui.item,ui.item.prevAll(".tabulator-row").length);
},
}
//if groups enabled, set sortable on groups, otherwise set it on main table
if(options.groupBy){
$(".tabulator-group-body", self.table).sortable(config);
}else{
self.table.sortable(config);
}
}
if(options.groupBy){
$(".tabulator-group", self.table).each(function(){
self._renderGroupHeader($(this));
});
self._sortElement(self.table, {}, "asc", true); //sort groups
}
//align column widths
self._colRender(!self.firstRender);
//style table rows
self._styleRows();
//show table once loading complete
// self.table.show();
//hide loader div
self._hideLoader(self);
self._trigger("renderComplete");
if(self.filterField){
self._trigger("filterComplete");
}
if(self.options.pagination){
self.options.pageLoaded(self.paginationCurrentPage);
}
//trigger progressive render
if(progressiveRender && self.paginationCurrentPage < self.paginationMaxPage && self.tableHolder[0].scrollHeight <= self.tableHolder.innerHeight()){
self.paginationCurrentPage++;
self._renderTable(true);
}
self.firstRender = false;
},
//render individual rows
_renderRow:function(item){
var self = this;
var row = $('<div class="tabulator-row" data-id="' + item[self.options.index] + '"></div>');
//bind row data to row
row.data("data", item);
//bind row click events
row.on("click", function(e){self._rowClick(e, row, item)});
row.on("contextmenu", function(e){self._rowContext(e, row, item)});
//add row handle if movable rows enabled
if(self.options.movableRows){
var handle = $("<div class='tabulator-row-handle'></div>");
handle.append(self.options.movableRowHandle);
row.append(handle);
}
$.each(self.options.columns, function(i, column) {
//deal with values that arnt declared
var value = typeof(item[column.field]) == 'undefined' ? "" : item[column.field];
// set empty values to not break search
if(typeof(item[column.field]) == 'undefined'){
item[column.field] = "";
}
//set column text alignment
var align = typeof(column.align) == 'undefined' ? "left" : column.align;
//allow tabbing on editable cells
var tabbable = column.editable || column.editor ? "tabindex='0'" : "";
var visibility = column.visible ? "inline-block" : "none";
//set style as string rather than using .css for massive improvement in rendering time
var cellStyle = "text-align: " + align + "; display:" + visibility + ";";
var cell = $("<div class='tabulator-cell " + column.cssClass + "' " + tabbable + " style='" + cellStyle + "' data-index='" + i + "' data-field='" + column.field + "' data-value='" + self._safeString(value) + "' ></div>");
//add tooltip to cell
self._generateTooltip(cell, item, column.tooltip);
//match editor if one exists
if (column.editable || column.editor){
if(column.editor){
var editor = column.editor;
}else{
var editor = self.editors[column.formatter] ? column.formatter: "input";
}
cell.data("editor", editor);
}
//format cell contents
cell.data("formatter", column.formatter);
cell.data("formatterParams", column.formatterParams);
cell.html(self._formatCell(column.formatter, value, item, cell, row, column.formatterParams));
//bind cell click function
if(typeof(column.onClick) == "function"){
cell.on("click", function(e){self._cellClick(e, cell)});
}else{
//handle input replacement on editable cells
if(cell.data("editor")){
cell.on("click", function(e){
if(!$(this).hasClass("tabulator-editing")){
$(this).focus();
}
});
cell.on("focus", function(e){
e.stopPropagation();
//Load editor
var editorFunc = typeof(cell.data("editor")) == "string" ? self.editors[cell.data("editor")] : cell.data("editor");
var cellEditor = editorFunc(cell, cell.data("value"));
//if editor returned, add to DOM, if false, abort edit
if(cellEditor !== false){
cell.addClass("tabulator-editing");
cell.empty();
cell.append(cellEditor);
//prevent editing from tirggering rowClick event
cell.children().click(function(e){
e.stopPropagation();
})
}else{
cell.blur();
}
});
}
}
row.append(cell);
});
return row;
},
//render group element
_renderGroup:function(value){
var group = $("<div class='tabulator-group show' data-value='" + value + "'><div class='tabulator-group-header'></div><div class='tabulator-group-body'></div></div>");
return group;
},
//render group header
_renderGroupHeader:function(group){
var self = this;
//create sortable arrow chevrons
var arrow = $("<div class='tabulator-arrow'></div>")
.on("click", function(){
$(this).closest(".tabulator-group").toggleClass("show");
});
var data = [];
$(".tabulator-row", group).each(function(){
data.push($(this).data("data"));
});
$(".tabulator-group-header", group)
.html(arrow)
.append(self.options.groupHeader(group.data("value"), $(".tabulator-row", group).length, data));
},
//show loader blockout div
_showLoader:function(self, msg){
if(self.options.showLoader){
$(".tabulator-loader-msg", self.loaderDiv).empty().append(msg);
$(".tabulator-loader-msg", self.loaderDiv).css({"margin-top":(self.element.innerHeight() / 2) - ($(".tabulator-loader-msg", self.loaderDiv).outerHeight()/2)})
self.element.append(self.loaderDiv);
}
},
//hide loader
_hideLoader:function(self){
$(".tablulator-loader", self.element).remove();
},
//generate tooltip text
_generateTooltip:function(cell, data, tooltip){
var self = this;
var tooltip = tooltip || tooltip === false ? tooltip : self.options.tooltips;
if(tooltip === true){
tooltip = cell.data("value");
}else if(typeof(tooltip) == "function"){
tooltip = tooltip(cell.data("field"), cell.data("value"), data);
}
if(tooltip){
cell.attr("title", tooltip);
}else{
cell.attr("title", "");
}
},
////////////////// Column Styling //////////////////
//resize a colum to specified width
_resizeCol:function(index, width){
var self = this;
$(".tabulator-cell[data-index=" + index + "], .tabulator-col[data-index=" + index + "]",this.element).css({width:width})
//reinstate right edge on table if fitted columns resized
if(self.options.fitColumns){
$(".tabulator-row .tabulator-cell:last-of-type",self.element).css("border-right","");
$(".tabulator-col:last",self.element).css("border-right","");
}
self._vertAlignColHeaders();
},
//set all headers to the same height
_vertAlignColHeaders:function(){
if(self.header){
var headerHeight = self.header.outerHeight()
$(".tabulator-col, .tabulator-col-row-handle", self.header).css({"height":""}).css({"height":self.header.innerHeight() + "px"});
if(self.options.height && headerHeight != self.header.outerHeight()){
self.tableHolder.css({
"min-height":"calc(100% - " + self.header.outerHeight() + "px)",
"max-height":"calc(100% - " + self.header.outerHeight() + "px)",
});
}
}
},
//layout columns
_colLayout:function(){
var self = this;
var options = self.options;
var element = self.element;
self.header.empty();
//create sortable arrow chevrons
var arrow = $("<div class='tabulator-arrow'></div>");
//add column for row handle if movable rows enabled
if(options.movableRows){
var handle = $('<div class="tabulator-col-row-handle"> </div>');
self.header.append(handle);
}
//setup movable columns
if(options.movableCols){
self.header.sortable({
axis: "x",
opacity:1,
cancel:".tabulator-col-row-handle, .tabulator-col[data-field=''], .tabulator-col[data-field=undefined]",
start: function(event, ui){
ui.placeholder.css({"display":"inline-block", "width":ui.item.outerWidth()});
},
change: function(event, ui){
ui.placeholder.css({"display":"inline-block", "width":ui.item.outerWidth()});
var field = ui.item.data("field");
var newPos = ui.placeholder.next(".tabulator-col").data("field")
//cover situation where user moves back to original position
if(newPos == field){
newPos = ui.placeholder.next(".tabulator-col").next(".tabulator-col").data("field")
}
$(".tabulator-row", self.table).each(function(){
if(newPos){
$(".tabulator-cell[data-field=" + field + "]", $(this)).insertBefore($(".tabulator-cell[data-field=" + newPos + "]", $(this)))
}else{
$(this).append($(".tabulator-cell[data-field=" + field + "]", $(this)))
}
})
},
update: function(event, ui) {
//update columns array with new positional data
var fromField = ui.item.data("field")
var toField = ui.item.next(".tabulator-col").data("field")
var from = null;
var to = toField ? null : options.columns.length;
$.each(options.columns, function(i, column) {
if(column.field && column.field == fromField){
from = i;
}
if(from !== null){
return false;
}
});
var columns = options.columns.splice(from, 1)[0]
$.each(options.columns, function(i, column) {
if(column.field && column.field == toField){
to = i;
}
if(to !== null){
return false;
}
});
options.columns.splice(to , 0, columns);
//trigger callback
options.colMoved(ui.item.data("field"), options.columns);
if(self.options.columnLayoutCookie){
self._setColCookie();
}
},
});
}//
$.each(options.columns, function(i, column) {
column.index = i;
column.sorter = typeof(column.sorter) == "undefined" ? "string" : column.sorter;
column.sortable = typeof(column.sortable) == "undefined" ? options.sortable : column.sortable;
column.sortable = typeof(column.field) == "undefined" ? false : column.sortable;
column.visible = typeof(column.visible) == "undefined" ? true : column.visible;
column.cssClass = typeof(column.cssClass) == "undefined" ? "" : column.cssClass;
if(options.sortBy == column.field){
var sortdir = " data-sortdir='" + options.sortDir + "' ";
self.sortCurCol= column;
self.sortCurDir = options.sortDir;
}else{
var sortdir = "";
}
var title = column.title ? column.title : " ";
var visibility = column.visible ? "inline-block" : "none";
var col = $('<div class="tabulator-col ' + column.cssClass + '" style="display:' + visibility + '" data-index="' + i + '" data-field="' + column.field + '" data-sortable=' + column.sortable + sortdir + ' >' + title + '</div>');
if(typeof(column.width) != "undefined"){
column.width = isNaN(column.width) ? column.width : column.width + "px"; //format number
col.data("width", column.width);
col.css({width:column.width});
}
//sort tabl click binding
if(column.sortable){
col.on("click", function(){
if(!self.mouseDragOut){ //prevent accidental trigger my mouseup on column drag
self._sortClick(column, col); //trigger sort
}
self.mouseDragOut = false;
})
}
self.header.append(col);
});
//handle resizable columns
if(self.options.colResizable){
//create resize handle
var handle = $("<div class='tabulator-handle'></div>");
var prevHandle = $("<div class='tabulator-handle prev'></div>")
$(".tabulator-col", self.header).append(handle);
$(".tabulator-col", self.header).append(prevHandle);
$(".tabulator-col .tabulator-handle", self.header).on("mousedown", function(e){
e.stopPropagation(); //prevent resize from interfereing with movable columns
var colElement = !$(this).hasClass("prev") ? $(this).closest(".tabulator-col") : $(this).closest(".tabulator-col").prev(".tabulator-col");
if(colElement){
self.mouseDrag = e.screenX;
self.mouseDragWidth = colElement.outerWidth();
self.mouseDragElement = colElement;
}
$("body").on("mouseup", endColMove);
})
self.element.on("mousemove", function(e){
if(self.mouseDrag){
self.mouseDragElement.css({width: self.mouseDragWidth + (e.screenX - self.mouseDrag)})
self._resizeCol(self.mouseDragElement.data("index"), self.mouseDragElement.outerWidth());
}
})
var endColMove = function(e){
if(self.mouseDrag){
e.stopPropagation();
e.stopImmediatePropagation();
$("body").off("mouseup", endColMove);
self.mouseDragOut = true;
self._resizeCol(self.mouseDragElement.data("index"), self.mouseDragElement.outerWidth());
$.each(self.options.columns, function(i, item) {
if(item.field == self.mouseDragElement.data("field")){
item.width = self.mouseDragElement.outerWidth();
}
});
if(self.options.columnLayoutCookie){
self._setColCookie();
}
self.mouseDrag = false;
self.mouseDragWidth = false;
self.mouseDragElement = false;
}
}
}
element.append(self.header);
self.tableHolder.append(self.table);
element.append(self.tableHolder);
//add pagination footer if needed
if(self.footer){
element.append(self.footer);
var footerHeight = self.header.outerHeight() + self.footer.outerHeight();
self.tableHolder.css({
"min-height":"calc(100% - " + footerHeight + "px)",
"max-height":"calc(100% - " + footerHeight + "px)",
});
}else{
if(self.options.height){
self.tableHolder.css({
"min-height":"calc(100% - " + self.header.outerHeight() + "px)",
"max-height":"calc(100% - " + self.header.outerHeight() + "px)",
});
}
}
//set paginationSize if pagination enabled, height is set but no pagination number set, else set to ten;
if(self.options.pagination && !self.options.paginationSize){
if(self.options.height){
self.options.paginationSize = Math.floor(self.tableHolder.outerHeight() / (self.header.outerHeight() - 1))
}else{
self.options.paginationSize = 10;
}
}
element.on("editval", ".tabulator-cell", function(e, value){
if($(this).is(":focus")){$(this).blur()}
self._cellDataChange($(this), value);
})
element.on("editcancel", ".tabulator-cell", function(e, value){
self._cellDataChange($(this), $(this).data("value"));
})
//append sortable arrows to sortable headers
$(".tabulator-col[data-sortable=true]", self.header)
.data("sortdir", "desc")
.append(arrow.clone());
//render column headings
self._colRender();
if(self.firstRender && self.options.data){
// self.firstRender = false;
self._parseData(self.options.data);
}
},
//layout coluns on first render
_colRender:function(fixedwidth){
var self = this;
var options = self.options;
var table = self.table;
var header = self.header;
var element = self.element;
if(fixedwidth || !options.fitColumns){ //it columns have been resized and now data needs to match them
//free sized table
$.each(options.columns, function(i, column) {
colWidth = $(".tabulator-col[data-index=" + i + "]", element).outerWidth();
var col = $(".tabulator-cell[data-index=" + i + "]", element);
col.css({width:colWidth});
});
}else{
if(options.fitColumns){
//resize columns to fit in window
//remove right edge border on table if fitting to width to prevent double border
$(".tabulator-row .tabulator-cell:last-child, .tabulator-col:last",element).css("border-right","none");
if(self.options.fitColumns){
$(".tabulator-row", self.table).css({
"width":"100%",
})
}
var totWidth = options.movableRows ? self.element.innerWidth() - 30 : self.element.innerWidth();
var colCount = 0;
var widthIdeal = 0;
var widthIdealCount = 0;
var lastVariableCol = "";
$.each(options.columns, function(i, column) {
if(column.visible){
colCount++;
if(column.width){
var thisWidth = typeof(column.width) == "string" ? parseInt(column.width) : column.width;
widthIdeal += thisWidth;
widthIdealCount++;
}else{
lastVariableCol = column.field;
}
}
});
var colWidth = totWidth / colCount;
var proposedWidth = Math.floor((totWidth - widthIdeal) / (colCount - widthIdealCount))
//prevent underflow on non integer width tables
var gapFill = totWidth - widthIdeal - (proposedWidth * (colCount - widthIdealCount));
gapFill = gapFill > 0 ? gapFill : 0;
if(proposedWidth >= parseInt(options.colMinWidth)){
$.each(options.columns, function(i, column) {
if(column.visible){
var newWidth = column.width ? column.width : proposedWidth;
var col = $(".tabulator-cell[data-index=" + i + "], .tabulator-col[data-index=" + i + "]",element);
if(column.field == lastVariableCol){
col.css({width:newWidth + gapFill});
}else{
col.css({width:newWidth});
}
}
});
}else{
var col = $(".tabulator-cell, .tabulator-col",element);
col.css({width:colWidth});
}
}else{
//free sized table
$.each(options.columns, function(i, column) {
var col = $(".tabulator-cell[data-index=" + i + "], .tabulator-col[data-index=" + i+ "]",element)
if(column.width){
//reseize to match specified column width
max = column.width;
}else{
//resize columns to widest element
var max = 0;
col.each(function(){
max = $(this).outerWidth() > max ? $(this).outerWidth() : max
});
if(options.colMinWidth){
max = max < options.colMinWidth ? options.colMinWidth : max;
}
}
col.css({width:max});
});
}//
}
//vertically align headers
self._vertAlignColHeaders();
},
////////////////// Row Styling //////////////////
//style rows of the table
_styleRows:function(minimal){
var self = this;
if(!minimal){
//hover over rows
if(self.options.selectable){
$(".tabulator-row").addClass("selectable");
}else{
$(".tabulator-row").removeClass("selectable");
}
//apply row formatter
if(self.options.rowFormatter){
$(".tabulator-row", self.table).each(function(){
//allow row contents to be replaced with custom DOM elements
var newRow = self.options.rowFormatter($(this), $(this).data("data"));
if(newRow){
$(this).html(newRow)
}
});
}
}
// if(!self.options.height){
// var height = self.tableHolder.outerHeight() + self.header.outerHeight();
// if(self.footer){
// height += self.footer.outerHeight() + 1;
// }
// // self.element.css({height:height})
// }
//resize cells vertically to fit row contents
if(self.element.is(":visible")){
$(".tabulator-row", self.table).each(function(){
$(".tabulator-cell, .tabulator-row-handle", $(this)).css({"height":$(this).outerHeight() + "px"});
})
}
},
//format cell contents
_formatCell:function(formatter, value, data, cell, row, formatterParams){
var formatter = typeof(formatter) == "undefined" ? "plaintext" : formatter;
formatter = typeof(formatter) == "string" ? this.formatters[formatter] : formatter;
return formatter(value, data, cell, row, this.options, formatterParams);
},
////////////////// Table Interaction Handlers //////////////////
//carry out action on row click
_rowClick: function(e, row, data){
this.options.rowClick(e, row.data("id"), data, row);
},
//carry out action on row context
_rowContext: function(e, row, data){
e.preventDefault();
this.options.rowContext(e, row.data("id"), data, row);
},
//carry out action on cell click
_cellClick: function(e, cell){
var column = this.options.columns.filter(function(column) {
return column.index == cell.data("index");
});
column[0].onClick(e, cell, cell.data("value"), cell.closest(".tabulator-row").data("data") );
},
//handle cell data change
_cellDataChange: function(cell, value){
var self = this;
var row = cell.closest(".tabulator-row");
cell.removeClass("tabulator-editing");
//update cell data value
cell.data("value", value);
//update row data
var rowData = row.data("data");
var hasChanged = rowData[cell.data("field")] != value;
rowData[cell.data("field")] = value;
row.data("data", rowData);
//reformat cell data
cell.html(self._formatCell(cell.data("formatter"), value, rowData, cell, row, cell.data("formatterParams")));
if(hasChanged){
//triger event
self.options.rowEdit(rowData[self.options.index], rowData, row);
self._generateTooltip(cell, rowData, self._findColumn(cell.data("field")).tooltip);
}
self._styleRows();
self._trigger("dataEdited");
},
////////////////// Formatter/Sorter Helpers //////////////////
//return escaped string for attribute
_safeString: function(value){
return String(value).replace(/'/g, "'");
},
//format date for date comparison
_formatDate:function(dateString){
var format = this.options.dateFormat
var ypos = format.indexOf("yyyy");
var mpos = format.indexOf("mm");
var dpos = format.indexOf("dd");
if(dateString){
var formattedString = dateString.substring(ypos, ypos+4) + "-" + dateString.substring(mpos, mpos+2) + "-" + dateString.substring(dpos, dpos+2);
var newDate = Date.parse(formattedString)
}else{
var newDate = 0;
}
return isNaN(newDate) ? 0 : newDate;
},
////////////////// Default Sorter/Formatter/Editor Elements //////////////////
//custom data sorters
sorters:{
number:function(a, b){ //sort numbers
return parseFloat(String(a).replace(",","")) - parseFloat(String(b).replace(",",""));
},
string:function(a, b){ //sort strings
return String(a).toLowerCase().localeCompare(String(b).toLowerCase());
},
date:function(a, b){ //sort dates
return a - b;
},
boolean:function(a, b){ //sort booleans
var el1 = a === true || a === "true" || a === "True" || a === 1 ? 1 : 0;
var el2 = b === true || b === "true" || b === "True" || b === 1 ? 1 : 0;
return el1 - el2
},
alphanum:function(as, bs) {
var a, b, a1, b1, i= 0, L, rx= /(\d+)|(\D+)/g, rd= /\d/;
if(isFinite(as) && isFinite(bs)) return as - bs;
a= String(as).toLowerCase();
b= String(bs).toLowerCase();
if(a=== b) return 0;
if(!(rd.test(a) && rd.test(b))) return a> b? 1: -1;
a= a.match(rx);
b= b.match(rx);
L= a.length> b.length? b.length: a.length;
while(i < L){
a1= a[i];
b1= b[i++];
if(a1!== b1){
if(isFinite(a1) && isFinite(b1)){
if(a1.charAt(0)=== "0") a1= "." + a1;
if(b1.charAt(0)=== "0") b1= "." + b1;
return a1 - b1;
}
else return a1> b1? 1: -1;
}
}
return a.length > b.length;
},
},
//custom data formatters
formatters:{
plaintext:function(value, data, cell, row, options, formatterParams){ //plain text value
return value;
},
money:function(value, data, cell, row, options, formatterParams){
var number = parseFloat(value).toFixed(2);
var number = number.split('.');
var integer = number[0];
var decimal = number.length > 1 ? '.' + number[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(integer)) {
integer = integer.replace(rgx, '$1' + ',' + '$2');
}
return integer + decimal;
},
email:function(value, data, cell, row, options, formatterParams){
return "<a href='mailto:" + value + "'>" + value + "</a>";
},
link:function(value, data, cell, row, options, formatterParams){
return "<a href='" + value + "'>" + value + "</a>";
},
tick:function(value, data, cell, row, options, formatterParams){
var tick = '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>';
if(value === true || value === 'true' || value === 'True' || value === 1){
return tick;
}else{
return "";
}
},
tickCross:function(value, data, cell, row, options, formatterParams){
var tick = '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>';
var cross = '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#CE1515" d="M22.245,4.015c0.313,0.313,0.313,0.826,0,1.139l-6.276,6.27c-0.313,0.312-0.313,0.826,0,1.14l6.273,6.272 c0.313,0.313,0.313,0.826,0,1.14l-2.285,2.277c-0.314,0.312-0.828,0.312-1.142,0l-6.271-6.271c-0.313-0.313-0.828-0.313-1.141,0 l-6.276,6.267c-0.313,0.313-0.828,0.313-1.141,0l-2.282-2.28c-0.313-0.313-0.313-0.826,0-1.14l6.278-6.269 c0.313-0.312,0.313-0.826,0-1.14L1.709,5.147c-0.314-0.313-0.314-0.827,0-1.14l2.284-2.278C4.308,1.417,4.821,1.417,5.135,1.73 L11.405,8c0.314,0.314,0.828,0.314,1.141,0.001l6.276-6.267c0.312-0.312,0.826-0.312,1.141,0L22.245,4.015z"/></svg>';
if(value === true || value === 'true' || value === 'True' || value === 1){
return tick;
}else{
return cross;
}
},
star:function(value, data, cell, row, options, formatterParams){
var maxStars = formatterParams && formatterParams.stars ? formatterParams.stars : 5;
var stars=$("<span style='vertical-align:middle;'></span>");
value = parseInt(value) < maxStars ? parseInt(value) : maxStars;
var starActive = $('<svg width="14" height="14" viewBox="0 0 512 512" xml:space="preserve" style="margin:0 1px;"><polygon fill="#FFEA00" stroke="#C1AB60" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>');
var starInactive = $('<svg width="14" height="14" viewBox="0 0 512 512" xml:space="preserve" style="margin:0 1px;"><polygon fill="#D2D2D2" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>');
for(var i=1;i<= maxStars;i++){
var nextStar = i <= value ? starActive : starInactive;
stars.append(nextStar.clone());
}
cell.css({
"white-space": "nowrap",
"overflow": "hidden",
"text-overflow": "ellipsis",
})
return stars.html();
},
progress:function(value, data, cell, row, options, formatterParams){ //progress bar
//set default parameters
var max = formatterParams && formatterParams.max ? formatterParams.max : 100;
var min = formatterParams && formatterParams.min ? formatterParams.min : 0;
var color = formatterParams && formatterParams.color ? formatterParams.color : "#2DC214";
//make sure value is in range
value = parseFloat(value) <= max ? parseFloat(value) : max;
value = parseFloat(value) >= min ? parseFloat(value) : min;
//workout percentage
var percent = (max - min) / 100;
value = 100 - Math.round((value - min) / percent);
cell.css({
"min-width":"30px",
"position":"relative",
});
return "<div style='position:absolute; top:8px; bottom:8px; left:4px; right:" + value + "%; margin-right:4px; background-color:" + color + "; display:inline-block;' data-max='" + max + "' data-min='" + min + "'></div>"
},
color:function(value, data, cell, row, options, formatterParams){
cell.css({"background-color":value});
return "";
},
buttonTick:function(value, data, cell, row, options, formatterParams){
return '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>';
},
buttonCross:function(value, data, cell, row, options, formatterParams){
return '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#CE1515" d="M22.245,4.015c0.313,0.313,0.313,0.826,0,1.139l-6.276,6.27c-0.313,0.312-0.313,0.826,0,1.14l6.273,6.272 c0.313,0.313,0.313,0.826,0,1.14l-2.285,2.277c-0.314,0.312-0.828,0.312-1.142,0l-6.271-6.271c-0.313-0.313-0.828-0.313-1.141,0 l-6.276,6.267c-0.313,0.313-0.828,0.313-1.141,0l-2.282-2.28c-0.313-0.313-0.313-0.826,0-1.14l6.278-6.269 c0.313-0.312,0.313-0.826,0-1.14L1.709,5.147c-0.314-0.313-0.314-0.827,0-1.14l2.284-2.278C4.308,1.417,4.821,1.417,5.135,1.73 L11.405,8c0.314,0.314,0.828,0.314,1.141,0.001l6.276-6.267c0.312-0.312,0.826-0.312,1.141,0L22.245,4.015z"/></svg>';
},
},
//custom data editors
editors:{
input:function(cell, value){
//create and style input
var input = $("<input type='text'/>");
input.css({
"border":"1px",
"background":"transparent",
"padding":"4px",
"width":"100%",
"box-sizing":"border-box",
})
.val(value);
setTimeout(function(){
input.focus();
},100)
//submit new value on blur
input.on("change blur", function(e){
cell.trigger("editval", input.val());
});
//submit new value on enter
input.on("keydown", function(e){
if(e.keyCode == 13){
cell.trigger("editval", input.val());
}
});
return input;
},
number:function(cell, value){
//create and style input
var input = $("<input type='number'/>");
input.css({
"border":"1px",
"background":"transparent",
"padding":"4px",
"width":"100%",
"box-sizing":"border-box",
})
.val(value);
setTimeout(function(){
input.focus();
},100)
//submit new value on blur
input.on("blur", function(e){
cell.trigger("editval", input.val());
});
//submit new value on enter
input.on("keydown", function(e){
if(e.keyCode == 13){
cell.trigger("editval", input.val());
}
});
return input;
},
star:function(cell, value){
var maxStars = $("svg", cell).length;
var size = $("svg:first", cell).attr("width");
var stars=$("<div style='vertical-align:middle; padding:4px; display:inline-block; vertical-align:middle;'></div>");
value = parseInt(value) < maxStars ? parseInt(value) : maxStars;
var starActive = $('<svg width="' + size + '" height="' + size + '" class="tabulator-star-active" viewBox="0 0 512 512" xml:space="preserve" style="padding:0 1px;"><polygon fill="#488CE9" stroke="#014AAE" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>');
var starInactive = $('<svg width="' + size + '" height="' + size + '" class="tabulator-star-inactive" viewBox="0 0 512 512" xml:space="preserve" style="padding:0 1px;"><polygon fill="#010155" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>');
for(var i=1;i<= maxStars;i++){
var nextStar = i <= value ? starActive : starInactive;
stars.append(nextStar.clone());
}
//change number of active stars
var starChange = function(element){
if($(".tabulator-star-active", element.closest("div")).length != element.prevAll("svg").length + 1){
element.prevAll("svg").replaceWith(starActive.clone());
element.nextAll("svg").replaceWith(starInactive.clone());
element.replaceWith(starActive.clone());
}
}
stars.on("mouseover", "svg", function(e){
e.stopPropagation();
starChange($(this));
})
stars.on("mouseover", function(e){
$("svg", $(this)).replaceWith(starInactive.clone());
});
stars.on("click", function(e){
$(this).closest(".tabulator-cell").trigger("editval", 0);
});
stars.on("click", "svg", function(e){
var val = $(this).prevAll("svg").length + 1;
cell.trigger("editval", val);
});
cell.css({
"white-space": "nowrap",
"overflow": "hidden",
"text-overflow": "ellipsis",
})
cell.on("blur", function(){
$(this).trigger("editcancel");
});
//allow key based navigation
cell.on("keydown", function(e){
switch(e.keyCode){
case 39: //right arrow
starChange($(".tabulator-star-inactive:first", stars))
break;
case 37: //left arrow
var prevstar = $(".tabulator-star-active:last", stars).prev("svg")
if(prevstar.length){
starChange(prevstar)
}else{
$("svg", stars).replaceWith(starInactive.clone());
}
break;
case 13: //enter
cell.trigger("editval", $(".tabulator-star-active", stars).length);
break;
}
});
return stars;
},
progress:function(cell, value){
//set default parameters
var max = $("div", cell).data("max");
var min = $("div", cell).data("min");
//make sure value is in range
value = parseFloat(value) <= max ? parseFloat(value) : max;
value = parseFloat(value) >= min ? parseFloat(value) : min;
//workout percentage
var percent = (max - min) / 100;
value = 100 - Math.round((value - min) / percent);
cell.css({
padding:"0 4px",
});
var newVal = function(){
var newval = (percent * Math.round(bar.outerWidth() / (cell.width()/100))) + min;
cell.trigger("editval", newval);
}
var bar = $("<div style='position:absolute; top:8px; bottom:8px; left:4px; right:" + value + "%; margin-right:4px; background-color:#488CE9; display:inline-block; max-width:100%; min-width:0%;' data-max='" + max + "' data-min='" + min + "'></div>");
var handle = $("<div class='tabulator-progress-handle' style='position:absolute; right:0; top:0; bottom:0; width:5px;'></div>");
bar.append(handle);
handle.on("mousedown", function(e){
bar.data("mouseDrag", e.screenX);
bar.data("mouseDragWidth", bar.outerWidth());
})
handle.on("mouseover", function(){$(this).css({cursor:"ew-resize"})})
cell.on("mousemove", function(e){
if(bar.data("mouseDrag")){
bar.css({width: bar.data("mouseDragWidth") + (e.screenX - bar.data("mouseDrag"))})
}
})
cell.on("mouseup", function(e){
if(bar.data("mouseDrag")){
e.stopPropagation();
e.stopImmediatePropagation();
bar.data("mouseDragOut", true);
bar.data("mouseDrag", false);
bar.data("mouseDragWidth", false);
newVal();
}
});
//allow key based navigation
cell.on("keydown", function(e){
switch(e.keyCode){
case 39: //right arrow
bar.css({"width" : bar.width() + cell.width()/100});
break;
case 37: //left arrow
bar.css({"width" : bar.width() - cell.width()/100});
break;
case 13: //enter
newVal();
break;
}
});
cell.on("blur", function(){
$(this).trigger("editcancel");
});
return bar;
},
tickCross:function(cell, value){
//create and style input
var input = $("<input type='checkbox'/>");
input.css({
"border":"1px",
"background":"transparent",
"margin-top":"5px",
"box-sizing":"border-box",
})
.val(value);
setTimeout(function(){
input.focus();
},100)
if(value === true || value === 'true' || value === 'True' || value === 1){
input.prop("checked", true)
}else{
input.prop("checked", false)
}
//submit new value on blur
input.on("change blur", function(e){
cell.trigger("editval", input.is(":checked"));
});
//submit new value on enter
input.on("keydown", function(e){
if(e.keyCode == 13){
cell.trigger("editval", input.is(":checked"));
}
});
return input;
},
tick:function(cell, value){
//create and style input
var input = $("<input type='checkbox'/>");
input.css({
"border":"1px",
"background":"transparent",
"margin-top":"5px",
"box-sizing":"border-box",
})
.val(value);
setTimeout(function(){
input.focus();
},100)
if(value === true || value === 'true' || value === 'True' || value === 1){
input.prop("checked", true)
}else{
input.prop("checked", false)
}
//submit new value on blur
input.on("change blur", function(e){
cell.trigger("editval", input.is(":checked"));
});
//submit new value on enter
input.on("keydown", function(e){
if(e.keyCode == 13){
cell.trigger("editval", input.is(":checked"));
}
});
return input;
},
},
////////////////// Tabulator Desconstructor //////////////////
//deconstructor
_destroy: function() {
var self = this;
var element = self.element;
element.empty();
element.removeClass("tabulator");
},
});
})(); | tabulator.js | /*
* This file is part of the Tabulator package.
*
* (c) Oliver Folkerd <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
(function(){
'use strict';
$.widget("ui.tabulator", {
data:[],//array to hold data for table
activeData:[],//array to hold data that is active in the DOM
firstRender:true, //layout table widths correctly on first render
mouseDrag:false, //mouse drag tracker;
mouseDragWidth:false, //starting width of colum on mouse drag
mouseDragElement:false, //column being dragged
mouseDragOut:false, //catch to prevent mouseup on col drag triggering click on sort
sortCurCol:null,//column name of currently sorted column
sortCurDir:null,//column name of currently sorted column
filterField:null, //field to be filtered on data render
filterValue:null, //value to match on filter
filterType:null, //filter type
paginationCurrentPage:1, // pagination page
paginationMaxPage:1, // pagination maxpage
progressiveRenderTimer:null, //timer for progressiver rendering
loaderDiv: $("<div class='tablulator-loader'><div class='tabulator-loader-msg'></div></div>"), //loader blockout div
//setup options
options: {
colMinWidth:"40px", //minimum global width for a column
colResizable:true, //resizable columns
height:false, //height of tabulator
fitColumns:false, //fit colums to width of screen;
movableCols:false, //enable movable columns
movableRows:false, //enable movable rows
movableRowHandle:"<div></div><div></div><div></div>", //handle for movable rows
columnLayoutCookie:false, //store cookie with column _styles
columnLayoutCookieID:"", //id for stored cookie
pagination:false, //enable pagination
paginationSize:false, //size of pages
paginationAjax:false, //paginate internal or via ajax
paginationElement:false, //element to hold pagination numbers
progressiveRender:false, //enable progressive rendering
progressiveRenderSize:20, //block size for progressive rendering
progressiveRenderMargin:200, //disance in px before end of scroll before progressive render is triggered
tooltips: false, //Tool tip value
columns:[],//store for colum header info
data:false, //store for initial table data if set at construction
index:"id",
sortable:true, //global default for sorting
dateFormat: "dd/mm/yyyy", //date format to be used for sorting
sortBy:"id", //defualt column to sort by
sortDir:"desc", //default sort direction
groupBy:false, //enable table grouping and set field to group by
groupHeader:function(value, count, data){ //header layout function
return value + "<span>(" + count + " item)</span>";
},
rowFormatter:false, //row formatter callback
addRowPos:"bottom", //position to insert blank rows, top|bottom
selectable:true, //highlight rows on hover
ajaxURL:false, //url for ajax loading
ajaxParams:{}, //url for ajax loading
showLoader:true, //show loader while data loading
loader:"<div class='tabulator-loading'>Loading Data</div>", //loader element
loaderError:"<div class='tabulator-error'>Loading Error</div>", //loader element
rowClick:function(){}, //do action on row click
rowAdded:function(){}, //do action on row add
rowEdit:function(){}, //do action on row edit
rowDelete:function(){}, //do action on row delete
rowContext:function(){}, //context menu action
dataLoaded:function(){}, //callback for when data has been Loaded
rowMoved:function(){}, //callback for when row has moved
colMoved:function(){}, //callback for when column has moved
pageLoaded:function(){}, //calback for when a page is loaded
},
////////////////// Element Construction //////////////////
//constructor
_create: function() {
var self = this;
var element = self.element;
if(element.is("table")){
self._parseTable();
}else{
self._buildElement();
}
},
//parse table element to create data set
_parseTable:function(){
var self = this;
var element = self.element;
var options = self.options;
var hasIndex = false;
//build columns from table header if they havnt been set;
if(!options.columns.length){
var headers = $("th", element);
if(headers.length){
//create column array from headers
headers.each(function(index){
var col = {title:$(this).text(), field:$(this).text().toLowerCase().replace(" ", "_")};
var width = $(this).attr("width");
if(width){
col.width = width;
}
if(col.field == options.index){
hasIndex = true;
}
options.columns.push(col);
});
}else{
//create blank table headers
headers = $("tr:first td", element);
headers.each(function(index){
var col = {title:"", field:"col" + index};
var width = $(this).attr("width");
if(width){
col.width = width;
}
options.columns.push(col);
});
}
}
//iterate through table rows and build data set
$("tbody tr", element).each(function(rowIndex){
var item = {};
//create index if the dont exist in table
if(!hasIndex){
item[options.index] = rowIndex;
}
//add row data to item
$("td", $(this)).each(function(colIndex){
item[options.columns[colIndex].field] = $(this).text();
});
self.data.push(item);
});
//create new element
var newElement = $("<div></div>");
//transfer attributes to new element
var attributes = element.prop("attributes");
// loop through attributes and apply them on div
$.each(attributes, function() {
newElement.attr(this.name, this.value);
});
// replace table with div element
element.replaceWith(newElement);
options.data = self.data;
newElement.tabulator(options);
},
//build tabulator element
_buildElement: function() {
var self = this;
var options = self.options;
var element = self.element;
options.colMinWidth = isNaN(options.colMinWidth) ? options.colMinWidth : options.colMinWidth + "px";
if(options.height){
options.height = isNaN(options.height) ? options.height : options.height + "px";
element.css({"height": options.height});
}
if(options.data){
self.data = options.data;
}
element.addClass("tabulator");
self.header = $("<div class='tabulator-header'></div>")
self.tableHolder = $("<div class='tabulator-tableHolder'></div>");
var scrollTop = 0;
var scrollLeft = 0;
self.tableHolder.scroll(function(){
// if(scrollLeft != $(this).scrollLeft()){
self.header.css({"margin-left": "-1" * $(this).scrollLeft()});
// }
//trigger progressive rendering on scroll
if(self.options.progressiveRender && scrollTop != $(this).scrollTop() && scrollTop < $(this).scrollTop()){
if($(this)[0].scrollHeight - $(this).innerHeight() - $(this).scrollTop() < self.options.progressiveRenderMargin){
if(self.paginationCurrentPage < self.paginationMaxPage){
self.paginationCurrentPage++;
self._renderTable(true);
}
}
}
scrollTop = $(this).scrollTop();
});
//create scrollable table holder
self.table = $("<div class='tabulator-table'></div>");
//build pagination footer if needed
if(options.pagination){
if(!options.paginationElement){
options.paginationElement = $("<div class='tabulator-footer'></div>");
self.footer = options.paginationElement;
}
self.paginator = $("<span class='tabulator-paginator'><span class='tabulator-page' data-page='first'>First</span><span class='tabulator-page' data-page='prev'>Prev</span><span class='tabulator-pages'></span><span class='tabulator-page' data-page='next'>Next</span><span class='tabulator-page' data-page='last'>Last</span></span>");
self.paginator.on("click", ".tabulator-page", function(){
if(!$(this).hasClass("disabled")){
self.setPage($(this).data("page"));
}
});
options.paginationElement.append(self.paginator);
}
//layout columns
if(options.columnLayoutCookie){
self._getColCookie();
}else{
self._colLayout();
}
},
//set options
_setOption: function(option, value) {
var self = this;
//block update if option cannot be updated this way
if(["columns"].indexOf(option) > -1){
return false
}
//set option to value
$.Widget.prototype._setOption.apply( this, arguments );
//trigger appropriate table response
if(["colMinWidth", "colResizable", "fitColumns", "movableCols", "movableRows", "movableRowHandle", "sortable", "groupBy", "groupHeader", "rowFormatter", "selectable"].indexOf(option) > -1){
//triger rerender
self._renderTable();
}else if(["height", "pagination", "paginationSize", "tooltips"].indexOf(option) > -1){
//triger render/reset page
if(self.options.pagination){
self.setPage(1);
}else{
self._renderTable();
}
}else if(["dateFormat", "sortBy", "sortDir"].indexOf(option) > -1){
//trigger sort
if(self.sortCurCol){
self.sort(self.sortCurCol, self.sortCurDir);
}
}else if(["index"].indexOf(option) > -1){
//trigger reparse data
self._parseData(self.data);
}else if(["paginationElement"].indexOf(option) > -1){
//trigger complete redraw
}
},
////////////////// General Public Functions //////////////////
//get number of elements in dataset
dataCount:function(){
return this.data.length;
},
//redraw list without updating data
redraw:function(fullRedraw){
var self = this;
//redraw columns
if(self.options.fitColumns){
self._colRender();
}
//reposition loader if present
if(self.element.innerHeight() > 0){
$(".tabulator-loader-msg", self.loaderDiv).css({"margin-top":(self.element.innerHeight() / 2) - ($(".tabulator-loader-msg", self.loaderDiv).outerHeight()/2)})
}
//trigger ro restyle
self._styleRows(true);
if(fullRedraw){
self._renderTable();
}
},
////////////////// Column Manipulation //////////////////
//set column style cookie
_setColCookie:function(){
var self = this;
//set cookie ied
var cookieID = self.options.columnLayoutCookieID ? self.options.columnLayoutCookieID : self.element.attr("id") ? self.element.attr("id") : "";
cookieID = "tabulator-" + cookieID;
//set cookie expiration far in the future
var expDate = new Date();
expDate.setDate(expDate.getDate() + 10000);
//create array of column styles only
var columnStyles = [];
$.each(self.options.columns, function(i, column) {
var style = {
field: column.field,
width: column.width,
visible:column.visible,
};
columnStyles.push(style);
});
//JSON format column data
var data = JSON.stringify(columnStyles);
//save cookie
document.cookie = cookieID + "=" + data + "; expires=" + expDate.toUTCString();
},
//set Column style cookie
_getColCookie:function(){
var self = this;
//set cookie ied
var cookieID = self.options.columnLayoutCookieID ? self.options.columnLayoutCookieID : self.element.attr("id") ? self.element.attr("id") : "";
cookieID = "tabulator-" + cookieID;
//find cookie
var cookie = document.cookie;
var cookiePos = cookie.indexOf(cookieID+"=");
//if cookie exists, decode and load column data into tabulator
if(cookiePos > -1){
cookie = cookie.substr(cookiePos);
var end = cookie.indexOf(";");
if(end > -1){
cookie = cookie.substr(0, end);
}
cookie = cookie.replace(cookieID+"=", "")
self.setColumns(JSON.parse(cookie), true);
}else{
self._colLayout();
}
},
//set tabulator columns
setColumns: function(columns, update){
var self = this;
var oldColumns = self.options.columns;
//if updateing columns work through exisiting column data
if(update){
var newColumns = [];
//iterate through each of the new columns
$.each(columns, function(i, column) {
//find a match in the original column array
var find = column.field;
//var find = column.field == "" ? column : column.field;
$.each(self.options.columns, function(i, origColumn) {
var match = typeof(find) == "object" ? origColumn == find : origColumn.field == find;
//if matching, update layout data and add to new column array
if(match){
var result = self.options.columns.splice(i, 1)[0];
result.width = column.width;
result.visible = column.visible;
newColumns.push(result);
return false;
}
});
});
//if any aditional columns left add them to the end of the table
if(self.options.columns.length > 0){
newColumns.concat(self.options.columns);
}
//replace old columns with new
self.options.columns = newColumns;
//Trigger Redraw
self._colLayout();
}else{
// if replaceing columns, replace columns array with new
self.options.columns = columns;
//Trigger Redraw
self._colLayout();
}
},
//get tabulator columns
getColumns: function(){
var self = this;
return self.options.columns;
},
//find column
_findColumn:function(field){
var self = this;
var result = false
$.each(self.options.columns, function(i, column) {
if(typeof(field) == "object"){
if(column == field){
result = column;
return false;
}
}else{
if(column.field == field){
result = column;
return false;
}
}
});
return result;
},
//hide column
hideCol: function(field){
var self = this;
var column = false;
$.each(self.options.columns, function(i, item) {
if(item.field == field){
column = i;
return false;
}
});
if(column === false){
return false;
}else{
self.options.columns[column].visible = false;
$(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).hide();
self._renderTable();
if(self.options.columnLayoutCookie){
self._setColCookie();
}
return true;
}
},
//show column
showCol: function(field){
var self = this;
var column = false;
$.each(self.options.columns, function(i, item) {
if(item.field == field){
column = i;
return false;
}
});
if(column === false){
return false;
}else{
self.options.columns[column].visible = true;
$(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).show();
self._renderTable();
if(self.options.columnLayoutCookie){
self._setColCookie();
}
return true;
}
},
//toggle column visibility
toggleCol: function(field){
var self = this;
var column = false;
$.each(self.options.columns, function(i, item) {
if(item.field == field){
column = i;
return false;
}
});
if(column === false){
return false;
}else{
self.options.columns[column].visible = !self.options.columns[column].visible;
if(self.options.columns[column].visible){
$(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).show();
}else{
$(".tabulator-col[data-field=" + field + "], .tabulator-cell[data-field=" + field + "]", self.element).hide();
}
if(self.options.columnLayoutCookie){
self._setColCookie();
}
self._renderTable();
return true;
}
},
////////////////// Row Manipulation //////////////////
//delete row from table by id
deleteRow: function(item){
var self = this;
var id = typeof(item) == "number" ? item : item.data("data")[self.options.index]
var row = typeof(item) == "number" ? $("[data-id=" + item + "]", self.element) : item;
var rowData = row.data("data");
rowData.tabulator_delete_row = true;
//remove from data
var line = self.data.find(function(rowData){
return item.tabulator_delete_row;
});
if(line){
line = self.data.indexOf(line);
if(line > -1){
//remove row from data
self.data.splice(line, 1);
}
}
//remove from active data
line = self.activeData.find(function(item){
return item.tabulator_delete_row;
});
if(line){
line = self.activeData.indexOf(line);
if(line > -1){
//remove row from data
self.activeData.splice(line, 1);
}
}
var group = row.closest(".tabulator-group");
row.remove();
if(self.options.groupBy){
var length = $(".tabulator-row", group).length;
if(length){
var data = [];
$(".tabulator-row", group).each(function(){
data.push($(this).data("data"));
});
var header = $(".tabulator-group-header", group)
var arrow = $(".tabulator-arrow", header).clone(true,true);
header.empty()
header.append(arrow).append(self.options.groupHeader(group.data("value"), $(".tabulator-row", group).length, data));
}else{
group.remove();
}
}
//style table rows
self._styleRows();
//align column widths
self._colRender(!self.firstRender);
self._trigger("renderComplete");
self.options.rowDelete(id);
self._trigger("dataEdited");
},
//add blank row to table
addRow:function(item){
var self = this;
if(item){
item[self.options.index] = item[self.options.index]? item[self.options.index]: 0;
}else{
item = {id:0}
}
//add item to
//self.data.push(item);
//create blank row
var row = self._renderRow(item);
//append to top or bottom of table based on preference
if(self.options.addRowPos == "top"){
self.activeData.push(item);
self.table.prepend(row);
}else{
self.activeData.unshift(item);
self.table.append(row);
}
//align column widths
self._colRender(!self.firstRender);
self._trigger("renderComplete");
//style table rows
self._styleRows();
//triger event
self.options.rowAdded(item);
self._trigger("dataEdited");
},
////////////////// Data Manipulation //////////////////
//get array of data from the table
getData:function(){
var self = this;
return self.activeData;
},
//load data
setData:function(data, params){
this._trigger("dataLoading");
params = params ? params : {};
//show loader if needed
this._showLoader(this, this.options.loader)
if(typeof(data) === "string"){
if (data.indexOf("{") == 0 || data.indexOf("[") == 0){
//data is a json encoded string
this._parseData(jQuery.parseJSON(data));
}else{
//assume data is url, make ajax call to url to get data
this._getAjaxData(data, params);
}
}else{
if(data){
//asume data is already an object
this._parseData(data);
}else{
//no data provided, check if ajaxURL is present;
if(this.options.ajaxURL){
this._getAjaxData(this.options.ajaxURL, params);
}else{
//empty data
this._parseData([]);
}
}
}
},
//clear data
clear:function(){
this.table.empty();
this.data = [];
this._filterData();
},
//get json data via ajax
_getAjaxData:function(url, params){
var self = this;
var options = self.options;
$.ajax({
url: url,
type: "GET",
data:params,
async: true,
dataType:'json',
success: function (data) {
self._parseData(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Tablulator ERROR (ajax get): " + xhr.status + " - " + thrownError);
self._trigger("dataLoadError", xhr, thrownError);
self._showLoader(self, self.options.loaderError);
},
});
},
//parse and index data
_parseData:function(data){
var self = this;
var newData = [];
if(data.length){
if(typeof(data[0][self.options.index]) == "undefined"){
self.options.index = "_index";
$.each(data, function(i, item) {
newData[i] = item;
newData[i]["_index"] = i;
});
}else{
$.each(data, function(i, item) {
newData.push(item);
});
}
}
self.data = newData;
self.options.dataLoaded(data);
//filter incomming data
self._filterData();
},
////////////////// Data Filtering //////////////////
//filter data in table
setFilter:function(field, type, value){
var self = this;
self._trigger("filterStarted");
//set filter
if(field){
//set filter
self.filterField = field;
self.filterType = typeof(value) == "undefined" ? "=" : type;
self.filterValue = typeof(value) == "undefined" ? type : value;
}else{
//clear filter
self.filterField = null;
self.filterType = null;
self.filterValue = null;
}
//render table
this._filterData();
},
//clear filter
clearFilter:function(){
var self = this;
self.filterField = null;
self.filterType = null;
self.filterValue = null;
//render table
this._filterData();
},
//get current filter info
getFilter:function(){
var self = this;
if(self.filterField){
var filter = {
"field":self.filterField,
"type":self.filterType,
"value":self.filterValue,
};
return filter;
}else{
return false;
}
},
//filter data set
_filterData:function(){
var self = this;
//filter data set
if(self.filterField ){
self.activeData = self.data.filter(function(row){
return self._filterRow(row);
});
}else{
self.activeData = self.data;
}
//set the max pages available given the filter results
if(self.options.pagination){
self.paginationMaxPage = Math.ceil(self.activeData.length/self.options.paginationSize);
}
//sort or render data
if(self.sortCurCol){
self.sort(self.sortCurCol, self.sortCurDir);
}else{
//determine pagination information / render table
if(self.options.pagination){
self.setPage(1);
}else{
self._renderTable();
}
}
},
//check if row data matches filter
_filterRow:function(row){
var self = this;
// if no filter set display row
if(!self.filterField){
return true;
}else{
if(typeof(self.filterField) == "function"){
return self.filterField(row);
}else{
var value = row[self.filterField];
var term = self.filterValue;
switch(self.filterType){
case "=": //equal to
return value == term ? true : false;
break;
case "<": //less than
return value < term ? true : false;
break;
case "<=": //less than or equal too
return value <= term ? true : false;
break;
case ">": //greater than
return value > term ? true : false;
break;
case ">=": //greater than or equal too
return value >= term ? true : false;
break;
case "!=": //not equal to
return value != term ? true : false;
break;
case "like": //text like
return value.toLowerCase().indexOf(term.toLowerCase()) > -1 ? true : false;
break;
default:
return false;
}
}
}
return false;
},
////////////////// Data Sorting //////////////////
//handle user clicking on column header sort
_sortClick: function(column, element){
var self = this;
if (element.data("sortdir") == "desc"){
element.data("sortdir", "asc");
}else{
element.data("sortdir", "desc");
}
self.sort(column, element.data("sortdir"));
},
// public sorter function
sort: function(sortList, dir){
var self = this;
var header = self.header;
var options = this.options;
if(!Array.isArray(sortList)){
sortList = [{field: sortList, dir:dir}];
}
$.each(sortList, function(i, item) {
//convert colmun name to column object
if(typeof(item.field) == "string"){
$.each(options.columns, function(i, col) {
if(col.field == item.field){
item.field = col;
return false;
}
});
}
//reset all column sorts
$(".tabulator-col[data-sortable=true][data-field!=" + item.field.field + "]", self.header).data("sortdir", "desc");
$(".tabulator-col .tabulator-arrow", self.header).removeClass("asc desc")
var element = $(".tabulator-col[data-field='" + item.field.field + "']", header);
if (dir == "asc"){
$(".tabulator-arrow", element).removeClass("desc").addClass("asc");
}else{
$(".tabulator-arrow", element).removeClass("asc").addClass("desc");
}
self._sorter(item.field, item.dir, sortList, i);
});
self._trigger("sortComplete");
//determine pagination information / render table
if(self.options.pagination){
self.setPage(1);
}else{
self._renderTable();
}
},
//sort table
_sorter: function(column, dir, sortList, i){
var self = this;
var table = self.table;
var options = self.options;
var data = self.data;
self._trigger("sortStarted");
self.sortCurCol = column;
self.sortCurDir = dir;
self._sortElement(table, column, dir, sortList, i);
},
//itterate through nested sorters
_sortElement:function(element, column, dir, sortList, i){
var self = this;
self.activeData = self.activeData.sort(function(a,b){
var result = self._processSorter(a, b, column, dir);
//if results match recurse through previous searchs to be sure
if(result == 0 && i){
for(var j = i-1; j>= 0; j--){
result = self._processSorter(a, b, sortList[j].field, sortList[j].dir);
if(result != 0){
break;
}
}
}
return result;
})
},
//process individual sort functions on active data
_processSorter:function(a, b, column, dir){
var self = this;
//switch elements depending on search direction
var el1 = dir == "asc" ? a : b;
var el2 = dir == "asc" ? b : a;
el1 = el1[column.field];
el2 = el2[column.field];
//workaround to format dates correctly
a = column.sorter == "date" ? self._formatDate(el1) : el1;
b = column.sorter == "date" ? self._formatDate(el2) : el2;
//run sorter
var sorter = typeof(column.sorter) == "undefined" ? "string" : column.sorter;
sorter = typeof(sorter) == "string" ? self.sorters[sorter] : sorter;
return sorter(a, b);
},
////////////////// Data Pagination //////////////////
//get current page number
getPage:function(){
var self = this;
return self.options.pagination ? self.paginationCurrentPage : false;
},
//set current paginated page
setPage:function(page){
var self = this;
if(Number.isInteger(page) && page > 0 && page <= self.paginationMaxPage){
self.paginationCurrentPage = page;
}else{
switch(page){
case "first":
self.paginationCurrentPage = 1;
break;
case "prev":
if(self.paginationCurrentPage > 1){
self.paginationCurrentPage--;
}
break;
case "next":
if(self.paginationCurrentPage < self.paginationMaxPage){
self.paginationCurrentPage++;
}
break;
case "last":
self.paginationCurrentPage = self.paginationMaxPage;
break;
}
}
self._layoutPageSelector();
self._renderTable();
},
//set page size for the table
setPageSize:function(size){
var self = this;
self.options.paginationSize = size;
self._filterData();
},
//create page selector layout for current page
_layoutPageSelector:function(){
var self = this;
var min = 1, max = self.paginationMaxPage;
var pages = $(".tabulator-pages", self.paginator);
pages.empty();
var spacer = $("<span> ... </span>");
if(self.paginationMaxPage > 10){
if(self.paginationCurrentPage <= 4){
max = 5;
}else if(self.paginationCurrentPage > self.paginationMaxPage - 4){
min = self.paginationMaxPage - 4;
pages.append(spacer.clone());
}else{
min = self.paginationCurrentPage - 2;
max = self.paginationCurrentPage + 2;
pages.append(spacer.clone());
}
}
for(var i = min; i <= max; ++i){
var active = i == self.paginationCurrentPage ? "active" : "";
pages.append("<span class='tabulator-page " + active + "' data-page='" + i + "'>" + i + "</span>");
}
if(self.paginationMaxPage > 10){
if(self.paginationCurrentPage <= 4 || self.paginationCurrentPage <= self.paginationMaxPage - 4){
pages.append(spacer.clone());
}
}
$(".tabulator-page", self.paginator).removeClass("disabled");
if(self.paginationCurrentPage == 1){
$(".tabulator-page[data-page=first], .tabulator-page[data-page=prev]", self.paginator).addClass("disabled");
}
if(self.paginationCurrentPage == self.paginationMaxPage){
$(".tabulator-page[data-page=next], .tabulator-page[data-page=last]", self.paginator).addClass("disabled");
}
},
////////////////// Render Data to Table //////////////////
//render active data to table rows
_renderTable:function(progressiveRender){
var self = this;
var options = self.options
this._trigger("renderStarted");
//show loader if needed
self._showLoader(self, self.options.loader)
if(!progressiveRender){
clearTimeout(self.progressiveRenderTimer);
//hide table while building
// self.table.hide();
//clear data from table before loading new
self.table.empty();
}
if(!options.pagination && options.progressiveRender && !progressiveRender){
self.paginationCurrentPage = 1;
self.paginationMaxPage = Math.ceil(self.activeData.length/self.options.progressiveRenderSize);
options.paginationSize = options.progressiveRenderSize;
progressiveRender = true;
}
var renderData = options.pagination || options.progressiveRender ? self.activeData.slice((self.paginationCurrentPage-1) * self.options.paginationSize, ((self.paginationCurrentPage-1) * self.options.paginationSize) + self.options.paginationSize) : self.activeData;
//build rows of table
renderData.forEach( function(item, i) {
var row = self._renderRow(item);
if(options.groupBy){
// if groups in use, render column in group
var groupVal = typeof(options.groupBy) == "function" ? options.groupBy(item) : item[options.groupBy];
var group = $(".tabulator-group[data-value='" + groupVal + "']", self.table);
//if group does not exist, build it
if(group.length == 0){
group = self._renderGroup(groupVal);
self.table.append(group);
}
$(".tabulator-group-body", group).append(row);
}else{
//if not grouping output row to table
self.table.append(row);
}
});
//enable movable rows
if(options.movableRows){
var moveBackground ="";
var moveBorder ="";
//sorter options
var config = {
handle:".tabulator-row-handle",
opacity: 1,
axis: "y",
start: function(event, ui){
moveBorder = ui.item.css("border");
moveBackground = ui.item.css("background-color");
ui.item.css({
"border":"1px solid #000",
"background":"#fff",
});
},
stop: function(event, ui){
ui.item.css({
"border": moveBorder,
"background":moveBackground,
});
},
update: function(event, ui) {
//restyle rows
self._styleRows();
//clear sorter arrows
$(".tabulator-col[data-sortable=true]", self.header).data("sortdir", "desc");
$(".tabulator-col .tabulator-arrow", self.header).removeClass("asc desc")
self.activeData = [];
//update active data to mach rows
$(".tabulator-row", self.table).each(function(){
self.activeData.push($(this).data("data"));
});
//trigger callback
options.rowMoved(ui.item.data("id"), ui.item.data("data"), ui.item,ui.item.prevAll(".tabulator-row").length);
},
}
//if groups enabled, set sortable on groups, otherwise set it on main table
if(options.groupBy){
$(".tabulator-group-body", self.table).sortable(config);
}else{
self.table.sortable(config);
}
}
if(options.groupBy){
$(".tabulator-group", self.table).each(function(){
self._renderGroupHeader($(this));
});
self._sortElement(self.table, {}, "asc", true); //sort groups
}
//align column widths
self._colRender(!self.firstRender);
//style table rows
self._styleRows();
//show table once loading complete
// self.table.show();
//hide loader div
self._hideLoader(self);
self._trigger("renderComplete");
if(self.filterField){
self._trigger("filterComplete");
}
if(self.options.pagination){
self.options.pageLoaded(self.paginationCurrentPage);
}
//trigger progressive render
if(progressiveRender && self.paginationCurrentPage < self.paginationMaxPage && self.tableHolder[0].scrollHeight <= self.tableHolder.innerHeight()){
self.paginationCurrentPage++;
self._renderTable(true);
}
self.firstRender = false;
},
//render individual rows
_renderRow:function(item){
var self = this;
var row = $('<div class="tabulator-row" data-id="' + item[self.options.index] + '"></div>');
//bind row data to row
row.data("data", item);
//bind row click events
row.on("click", function(e){self._rowClick(e, row, item)});
row.on("contextmenu", function(e){self._rowContext(e, row, item)});
//add row handle if movable rows enabled
if(self.options.movableRows){
var handle = $("<div class='tabulator-row-handle'></div>");
handle.append(self.options.movableRowHandle);
row.append(handle);
}
$.each(self.options.columns, function(i, column) {
//deal with values that arnt declared
var value = typeof(item[column.field]) == 'undefined' ? "" : item[column.field];
// set empty values to not break search
if(typeof(item[column.field]) == 'undefined'){
item[column.field] = "";
}
//set column text alignment
var align = typeof(column.align) == 'undefined' ? "left" : column.align;
//allow tabbing on editable cells
var tabbable = column.editable || column.editor ? "tabindex='0'" : "";
var visibility = column.visible ? "inline-block" : "none";
//set style as string rather than using .css for massive improvement in rendering time
var cellStyle = "text-align: " + align + "; display:" + visibility + ";";
var cell = $("<div class='tabulator-cell " + column.cssClass + "' " + tabbable + " style='" + cellStyle + "' data-index='" + i + "' data-field='" + column.field + "' data-value='" + self._safeString(value) + "' ></div>");
//add tooltip to cell
self._generateTooltip(cell, item, column.tooltip);
//match editor if one exists
if (column.editable || column.editor){
if(column.editor){
var editor = column.editor;
}else{
var editor = self.editors[column.formatter] ? column.formatter: "input";
}
cell.data("editor", editor);
}
//format cell contents
cell.data("formatter", column.formatter);
cell.data("formatterParams", column.formatterParams);
cell.html(self._formatCell(column.formatter, value, item, cell, row, column.formatterParams));
//bind cell click function
if(typeof(column.onClick) == "function"){
cell.on("click", function(e){self._cellClick(e, cell)});
}else{
//handle input replacement on editable cells
if(cell.data("editor")){
cell.on("click", function(e){
if(!$(this).hasClass("tabulator-editing")){
$(this).focus();
}
});
cell.on("focus", function(e){
e.stopPropagation();
//Load editor
var editorFunc = typeof(cell.data("editor")) == "string" ? self.editors[cell.data("editor")] : cell.data("editor");
var cellEditor = editorFunc(cell, cell.data("value"));
//if editor returned, add to DOM, if false, abort edit
if(cellEditor !== false){
cell.addClass("tabulator-editing");
cell.empty();
cell.append(cellEditor);
//prevent editing from tirggering rowClick event
cell.children().click(function(e){
e.stopPropagation();
})
}else{
cell.blur();
}
});
}
}
row.append(cell);
});
return row;
},
//render group element
_renderGroup:function(value){
var group = $("<div class='tabulator-group show' data-value='" + value + "'><div class='tabulator-group-header'></div><div class='tabulator-group-body'></div></div>");
return group;
},
//render group header
_renderGroupHeader:function(group){
var self = this;
//create sortable arrow chevrons
var arrow = $("<div class='tabulator-arrow'></div>")
.on("click", function(){
$(this).closest(".tabulator-group").toggleClass("show");
});
var data = [];
$(".tabulator-row", group).each(function(){
data.push($(this).data("data"));
});
$(".tabulator-group-header", group)
.html(arrow)
.append(self.options.groupHeader(group.data("value"), $(".tabulator-row", group).length, data));
},
//show loader blockout div
_showLoader:function(self, msg){
if(self.options.showLoader){
$(".tabulator-loader-msg", self.loaderDiv).empty().append(msg);
$(".tabulator-loader-msg", self.loaderDiv).css({"margin-top":(self.element.innerHeight() / 2) - ($(".tabulator-loader-msg", self.loaderDiv).outerHeight()/2)})
self.element.append(self.loaderDiv);
}
},
//hide loader
_hideLoader:function(self){
$(".tablulator-loader", self.element).remove();
},
//generate tooltip text
_generateTooltip:function(cell, data, tooltip){
var self = this;
var tooltip = tooltip || tooltip === false ? tooltip : self.options.tooltips;
if(tooltip === true){
tooltip = cell.data("value");
}else if(typeof(tooltip) == "function"){
tooltip = tooltip(cell.data("field"), cell.data("value"), data);
}
if(tooltip){
cell.attr("title", tooltip);
}else{
cell.attr("title", "");
}
},
////////////////// Column Styling //////////////////
//resize a colum to specified width
_resizeCol:function(index, width){
var self = this;
$(".tabulator-cell[data-index=" + index + "], .tabulator-col[data-index=" + index + "]",this.element).css({width:width})
//reinstate right edge on table if fitted columns resized
if(self.options.fitColumns){
$(".tabulator-row .tabulator-cell:last-of-type",self.element).css("border-right","");
$(".tabulator-col:last",self.element).css("border-right","");
}
self._vertAlignColHeaders();
},
//set all headers to the same height
_vertAlignColHeaders:function(){
var headerHeight = self.header.outerHeight()
$(".tabulator-col, .tabulator-col-row-handle", self.header).css({"height":""}).css({"height":self.header.innerHeight() + "px"});
if(self.options.height && headerHeight != self.header.outerHeight()){
self.tableHolder.css({
"min-height":"calc(100% - " + self.header.outerHeight() + "px)",
"max-height":"calc(100% - " + self.header.outerHeight() + "px)",
});
}
},
//layout columns
_colLayout:function(){
var self = this;
var options = self.options;
var element = self.element;
self.header.empty();
//create sortable arrow chevrons
var arrow = $("<div class='tabulator-arrow'></div>");
//add column for row handle if movable rows enabled
if(options.movableRows){
var handle = $('<div class="tabulator-col-row-handle"> </div>');
self.header.append(handle);
}
//setup movable columns
if(options.movableCols){
self.header.sortable({
axis: "x",
opacity:1,
cancel:".tabulator-col-row-handle, .tabulator-col[data-field=''], .tabulator-col[data-field=undefined]",
start: function(event, ui){
ui.placeholder.css({"display":"inline-block", "width":ui.item.outerWidth()});
},
change: function(event, ui){
ui.placeholder.css({"display":"inline-block", "width":ui.item.outerWidth()});
var field = ui.item.data("field");
var newPos = ui.placeholder.next(".tabulator-col").data("field")
//cover situation where user moves back to original position
if(newPos == field){
newPos = ui.placeholder.next(".tabulator-col").next(".tabulator-col").data("field")
}
$(".tabulator-row", self.table).each(function(){
if(newPos){
$(".tabulator-cell[data-field=" + field + "]", $(this)).insertBefore($(".tabulator-cell[data-field=" + newPos + "]", $(this)))
}else{
$(this).append($(".tabulator-cell[data-field=" + field + "]", $(this)))
}
})
},
update: function(event, ui) {
//update columns array with new positional data
var fromField = ui.item.data("field")
var toField = ui.item.next(".tabulator-col").data("field")
var from = null;
var to = toField ? null : options.columns.length;
$.each(options.columns, function(i, column) {
if(column.field && column.field == fromField){
from = i;
}
if(from !== null){
return false;
}
});
var columns = options.columns.splice(from, 1)[0]
$.each(options.columns, function(i, column) {
if(column.field && column.field == toField){
to = i;
}
if(to !== null){
return false;
}
});
options.columns.splice(to , 0, columns);
//trigger callback
options.colMoved(ui.item.data("field"), options.columns);
if(self.options.columnLayoutCookie){
self._setColCookie();
}
},
});
}//
$.each(options.columns, function(i, column) {
column.index = i;
column.sorter = typeof(column.sorter) == "undefined" ? "string" : column.sorter;
column.sortable = typeof(column.sortable) == "undefined" ? options.sortable : column.sortable;
column.sortable = typeof(column.field) == "undefined" ? false : column.sortable;
column.visible = typeof(column.visible) == "undefined" ? true : column.visible;
column.cssClass = typeof(column.cssClass) == "undefined" ? "" : column.cssClass;
if(options.sortBy == column.field){
var sortdir = " data-sortdir='" + options.sortDir + "' ";
self.sortCurCol= column;
self.sortCurDir = options.sortDir;
}else{
var sortdir = "";
}
var title = column.title ? column.title : " ";
var visibility = column.visible ? "inline-block" : "none";
var col = $('<div class="tabulator-col ' + column.cssClass + '" style="display:' + visibility + '" data-index="' + i + '" data-field="' + column.field + '" data-sortable=' + column.sortable + sortdir + ' >' + title + '</div>');
if(typeof(column.width) != "undefined"){
column.width = isNaN(column.width) ? column.width : column.width + "px"; //format number
col.data("width", column.width);
col.css({width:column.width});
}
//sort tabl click binding
if(column.sortable){
col.on("click", function(){
if(!self.mouseDragOut){ //prevent accidental trigger my mouseup on column drag
self._sortClick(column, col); //trigger sort
}
self.mouseDragOut = false;
})
}
self.header.append(col);
});
//handle resizable columns
if(self.options.colResizable){
//create resize handle
var handle = $("<div class='tabulator-handle'></div>");
var prevHandle = $("<div class='tabulator-handle prev'></div>")
$(".tabulator-col", self.header).append(handle);
$(".tabulator-col", self.header).append(prevHandle);
$(".tabulator-col .tabulator-handle", self.header).on("mousedown", function(e){
e.stopPropagation(); //prevent resize from interfereing with movable columns
var colElement = !$(this).hasClass("prev") ? $(this).closest(".tabulator-col") : $(this).closest(".tabulator-col").prev(".tabulator-col");
if(colElement){
self.mouseDrag = e.screenX;
self.mouseDragWidth = colElement.outerWidth();
self.mouseDragElement = colElement;
}
$("body").on("mouseup", endColMove);
})
self.element.on("mousemove", function(e){
if(self.mouseDrag){
self.mouseDragElement.css({width: self.mouseDragWidth + (e.screenX - self.mouseDrag)})
self._resizeCol(self.mouseDragElement.data("index"), self.mouseDragElement.outerWidth());
}
})
var endColMove = function(e){
if(self.mouseDrag){
e.stopPropagation();
e.stopImmediatePropagation();
$("body").off("mouseup", endColMove);
self.mouseDragOut = true;
self._resizeCol(self.mouseDragElement.data("index"), self.mouseDragElement.outerWidth());
$.each(self.options.columns, function(i, item) {
if(item.field == self.mouseDragElement.data("field")){
item.width = self.mouseDragElement.outerWidth();
}
});
if(self.options.columnLayoutCookie){
self._setColCookie();
}
self.mouseDrag = false;
self.mouseDragWidth = false;
self.mouseDragElement = false;
}
}
}
element.append(self.header);
self.tableHolder.append(self.table);
element.append(self.tableHolder);
//add pagination footer if needed
if(self.footer){
element.append(self.footer);
var footerHeight = self.header.outerHeight() + self.footer.outerHeight();
self.tableHolder.css({
"min-height":"calc(100% - " + footerHeight + "px)",
"max-height":"calc(100% - " + footerHeight + "px)",
});
}else{
if(self.options.height){
self.tableHolder.css({
"min-height":"calc(100% - " + self.header.outerHeight() + "px)",
"max-height":"calc(100% - " + self.header.outerHeight() + "px)",
});
}
}
//set paginationSize if pagination enabled, height is set but no pagination number set, else set to ten;
if(self.options.pagination && !self.options.paginationSize){
if(self.options.height){
self.options.paginationSize = Math.floor(self.tableHolder.outerHeight() / (self.header.outerHeight() - 1))
}else{
self.options.paginationSize = 10;
}
}
element.on("editval", ".tabulator-cell", function(e, value){
if($(this).is(":focus")){$(this).blur()}
self._cellDataChange($(this), value);
})
element.on("editcancel", ".tabulator-cell", function(e, value){
self._cellDataChange($(this), $(this).data("value"));
})
//append sortable arrows to sortable headers
$(".tabulator-col[data-sortable=true]", self.header)
.data("sortdir", "desc")
.append(arrow.clone());
//render column headings
self._colRender();
if(self.firstRender && self.options.data){
// self.firstRender = false;
self._parseData(self.options.data);
}
},
//layout coluns on first render
_colRender:function(fixedwidth){
var self = this;
var options = self.options;
var table = self.table;
var header = self.header;
var element = self.element;
if(fixedwidth || !options.fitColumns){ //it columns have been resized and now data needs to match them
//free sized table
$.each(options.columns, function(i, column) {
colWidth = $(".tabulator-col[data-index=" + i + "]", element).outerWidth();
var col = $(".tabulator-cell[data-index=" + i + "]", element);
col.css({width:colWidth});
});
}else{
if(options.fitColumns){
//resize columns to fit in window
//remove right edge border on table if fitting to width to prevent double border
$(".tabulator-row .tabulator-cell:last-child, .tabulator-col:last",element).css("border-right","none");
if(self.options.fitColumns){
$(".tabulator-row", self.table).css({
"width":"100%",
})
}
var totWidth = options.movableRows ? self.element.innerWidth() - 30 : self.element.innerWidth();
var colCount = 0;
var widthIdeal = 0;
var widthIdealCount = 0;
var lastVariableCol = "";
$.each(options.columns, function(i, column) {
if(column.visible){
colCount++;
if(column.width){
var thisWidth = typeof(column.width) == "string" ? parseInt(column.width) : column.width;
widthIdeal += thisWidth;
widthIdealCount++;
}else{
lastVariableCol = column.field;
}
}
});
var colWidth = totWidth / colCount;
var proposedWidth = Math.floor((totWidth - widthIdeal) / (colCount - widthIdealCount))
//prevent underflow on non integer width tables
var gapFill = totWidth - widthIdeal - (proposedWidth * (colCount - widthIdealCount));
gapFill = gapFill > 0 ? gapFill : 0;
if(proposedWidth >= parseInt(options.colMinWidth)){
$.each(options.columns, function(i, column) {
if(column.visible){
var newWidth = column.width ? column.width : proposedWidth;
var col = $(".tabulator-cell[data-index=" + i + "], .tabulator-col[data-index=" + i + "]",element);
if(column.field == lastVariableCol){
col.css({width:newWidth + gapFill});
}else{
col.css({width:newWidth});
}
}
});
}else{
var col = $(".tabulator-cell, .tabulator-col",element);
col.css({width:colWidth});
}
}else{
//free sized table
$.each(options.columns, function(i, column) {
var col = $(".tabulator-cell[data-index=" + i + "], .tabulator-col[data-index=" + i+ "]",element)
if(column.width){
//reseize to match specified column width
max = column.width;
}else{
//resize columns to widest element
var max = 0;
col.each(function(){
max = $(this).outerWidth() > max ? $(this).outerWidth() : max
});
if(options.colMinWidth){
max = max < options.colMinWidth ? options.colMinWidth : max;
}
}
col.css({width:max});
});
}//
}
//vertically align headers
self._vertAlignColHeaders();
},
////////////////// Row Styling //////////////////
//style rows of the table
_styleRows:function(minimal){
var self = this;
if(!minimal){
//hover over rows
if(self.options.selectable){
$(".tabulator-row").addClass("selectable");
}else{
$(".tabulator-row").removeClass("selectable");
}
//apply row formatter
if(self.options.rowFormatter){
$(".tabulator-row", self.table).each(function(){
//allow row contents to be replaced with custom DOM elements
var newRow = self.options.rowFormatter($(this), $(this).data("data"));
if(newRow){
$(this).html(newRow)
}
});
}
}
if(!self.options.height){
var height = self.tableHolder.outerHeight() + self.header.outerHeight();
if(self.footer){
height += self.footer.outerHeight() + 1;
}
self.element.css({height:height})
}
//resize cells vertically to fit row contents
$(".tabulator-row", self.table).each(function(){
$(".tabulator-cell, .tabulator-row-handle", $(this)).css({"height":$(this).outerHeight() + "px"});
})
},
//format cell contents
_formatCell:function(formatter, value, data, cell, row, formatterParams){
var formatter = typeof(formatter) == "undefined" ? "plaintext" : formatter;
formatter = typeof(formatter) == "string" ? this.formatters[formatter] : formatter;
return formatter(value, data, cell, row, this.options, formatterParams);
},
////////////////// Table Interaction Handlers //////////////////
//carry out action on row click
_rowClick: function(e, row, data){
this.options.rowClick(e, row.data("id"), data, row);
},
//carry out action on row context
_rowContext: function(e, row, data){
e.preventDefault();
this.options.rowContext(e, row.data("id"), data, row);
},
//carry out action on cell click
_cellClick: function(e, cell){
var column = this.options.columns.filter(function(column) {
return column.index == cell.data("index");
});
column[0].onClick(e, cell, cell.data("value"), cell.closest(".tabulator-row").data("data") );
},
//handle cell data change
_cellDataChange: function(cell, value){
var self = this;
var row = cell.closest(".tabulator-row");
cell.removeClass("tabulator-editing");
//update cell data value
cell.data("value", value);
//update row data
var rowData = row.data("data");
var hasChanged = rowData[cell.data("field")] != value;
rowData[cell.data("field")] = value;
row.data("data", rowData);
//reformat cell data
cell.html(self._formatCell(cell.data("formatter"), value, rowData, cell, row, cell.data("formatterParams")));
if(hasChanged){
//triger event
self.options.rowEdit(rowData[self.options.index], rowData, row);
self._generateTooltip(cell, rowData, self._findColumn(cell.data("field")).tooltip);
}
self._styleRows();
self._trigger("dataEdited");
},
////////////////// Formatter/Sorter Helpers //////////////////
//return escaped string for attribute
_safeString: function(value){
return String(value).replace(/'/g, "'");
},
//format date for date comparison
_formatDate:function(dateString){
var format = this.options.dateFormat
var ypos = format.indexOf("yyyy");
var mpos = format.indexOf("mm");
var dpos = format.indexOf("dd");
if(dateString){
var formattedString = dateString.substring(ypos, ypos+4) + "-" + dateString.substring(mpos, mpos+2) + "-" + dateString.substring(dpos, dpos+2);
var newDate = Date.parse(formattedString)
}else{
var newDate = 0;
}
return isNaN(newDate) ? 0 : newDate;
},
////////////////// Default Sorter/Formatter/Editor Elements //////////////////
//custom data sorters
sorters:{
number:function(a, b){ //sort numbers
return parseFloat(String(a).replace(",","")) - parseFloat(String(b).replace(",",""));
},
string:function(a, b){ //sort strings
return String(a).toLowerCase().localeCompare(String(b).toLowerCase());
},
date:function(a, b){ //sort dates
return a - b;
},
boolean:function(a, b){ //sort booleans
var el1 = a === true || a === "true" || a === "True" || a === 1 ? 1 : 0;
var el2 = b === true || b === "true" || b === "True" || b === 1 ? 1 : 0;
return el1 - el2
},
alphanum:function(as, bs) {
var a, b, a1, b1, i= 0, L, rx= /(\d+)|(\D+)/g, rd= /\d/;
if(isFinite(as) && isFinite(bs)) return as - bs;
a= String(as).toLowerCase();
b= String(bs).toLowerCase();
if(a=== b) return 0;
if(!(rd.test(a) && rd.test(b))) return a> b? 1: -1;
a= a.match(rx);
b= b.match(rx);
L= a.length> b.length? b.length: a.length;
while(i < L){
a1= a[i];
b1= b[i++];
if(a1!== b1){
if(isFinite(a1) && isFinite(b1)){
if(a1.charAt(0)=== "0") a1= "." + a1;
if(b1.charAt(0)=== "0") b1= "." + b1;
return a1 - b1;
}
else return a1> b1? 1: -1;
}
}
return a.length > b.length;
},
},
//custom data formatters
formatters:{
plaintext:function(value, data, cell, row, options, formatterParams){ //plain text value
return value;
},
money:function(value, data, cell, row, options, formatterParams){
var number = parseFloat(value).toFixed(2);
var number = number.split('.');
var integer = number[0];
var decimal = number.length > 1 ? '.' + number[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(integer)) {
integer = integer.replace(rgx, '$1' + ',' + '$2');
}
return integer + decimal;
},
email:function(value, data, cell, row, options, formatterParams){
return "<a href='mailto:" + value + "'>" + value + "</a>";
},
link:function(value, data, cell, row, options, formatterParams){
return "<a href='" + value + "'>" + value + "</a>";
},
tick:function(value, data, cell, row, options, formatterParams){
var tick = '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>';
if(value === true || value === 'true' || value === 'True' || value === 1){
return tick;
}else{
return "";
}
},
tickCross:function(value, data, cell, row, options, formatterParams){
var tick = '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>';
var cross = '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#CE1515" d="M22.245,4.015c0.313,0.313,0.313,0.826,0,1.139l-6.276,6.27c-0.313,0.312-0.313,0.826,0,1.14l6.273,6.272 c0.313,0.313,0.313,0.826,0,1.14l-2.285,2.277c-0.314,0.312-0.828,0.312-1.142,0l-6.271-6.271c-0.313-0.313-0.828-0.313-1.141,0 l-6.276,6.267c-0.313,0.313-0.828,0.313-1.141,0l-2.282-2.28c-0.313-0.313-0.313-0.826,0-1.14l6.278-6.269 c0.313-0.312,0.313-0.826,0-1.14L1.709,5.147c-0.314-0.313-0.314-0.827,0-1.14l2.284-2.278C4.308,1.417,4.821,1.417,5.135,1.73 L11.405,8c0.314,0.314,0.828,0.314,1.141,0.001l6.276-6.267c0.312-0.312,0.826-0.312,1.141,0L22.245,4.015z"/></svg>';
if(value === true || value === 'true' || value === 'True' || value === 1){
return tick;
}else{
return cross;
}
},
star:function(value, data, cell, row, options, formatterParams){
var maxStars = formatterParams && formatterParams.stars ? formatterParams.stars : 5;
var stars=$("<span style='vertical-align:middle;'></span>");
value = parseInt(value) < maxStars ? parseInt(value) : maxStars;
var starActive = $('<svg width="14" height="14" viewBox="0 0 512 512" xml:space="preserve" style="margin:0 1px;"><polygon fill="#FFEA00" stroke="#C1AB60" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>');
var starInactive = $('<svg width="14" height="14" viewBox="0 0 512 512" xml:space="preserve" style="margin:0 1px;"><polygon fill="#D2D2D2" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>');
for(var i=1;i<= maxStars;i++){
var nextStar = i <= value ? starActive : starInactive;
stars.append(nextStar.clone());
}
cell.css({
"white-space": "nowrap",
"overflow": "hidden",
"text-overflow": "ellipsis",
})
return stars.html();
},
progress:function(value, data, cell, row, options, formatterParams){ //progress bar
//set default parameters
var max = formatterParams && formatterParams.max ? formatterParams.max : 100;
var min = formatterParams && formatterParams.min ? formatterParams.min : 0;
var color = formatterParams && formatterParams.color ? formatterParams.color : "#2DC214";
//make sure value is in range
value = parseFloat(value) <= max ? parseFloat(value) : max;
value = parseFloat(value) >= min ? parseFloat(value) : min;
//workout percentage
var percent = (max - min) / 100;
value = 100 - Math.round((value - min) / percent);
cell.css({
"min-width":"30px",
"position":"relative",
});
return "<div style='position:absolute; top:8px; bottom:8px; left:4px; right:" + value + "%; margin-right:4px; background-color:" + color + "; display:inline-block;' data-max='" + max + "' data-min='" + min + "'></div>"
},
color:function(value, data, cell, row, options, formatterParams){
cell.css({"background-color":value});
return "";
},
buttonTick:function(value, data, cell, row, options, formatterParams){
return '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>';
},
buttonCross:function(value, data, cell, row, options, formatterParams){
return '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#CE1515" d="M22.245,4.015c0.313,0.313,0.313,0.826,0,1.139l-6.276,6.27c-0.313,0.312-0.313,0.826,0,1.14l6.273,6.272 c0.313,0.313,0.313,0.826,0,1.14l-2.285,2.277c-0.314,0.312-0.828,0.312-1.142,0l-6.271-6.271c-0.313-0.313-0.828-0.313-1.141,0 l-6.276,6.267c-0.313,0.313-0.828,0.313-1.141,0l-2.282-2.28c-0.313-0.313-0.313-0.826,0-1.14l6.278-6.269 c0.313-0.312,0.313-0.826,0-1.14L1.709,5.147c-0.314-0.313-0.314-0.827,0-1.14l2.284-2.278C4.308,1.417,4.821,1.417,5.135,1.73 L11.405,8c0.314,0.314,0.828,0.314,1.141,0.001l6.276-6.267c0.312-0.312,0.826-0.312,1.141,0L22.245,4.015z"/></svg>';
},
},
//custom data editors
editors:{
input:function(cell, value){
//create and style input
var input = $("<input type='text'/>");
input.css({
"border":"1px",
"background":"transparent",
"padding":"4px",
"width":"100%",
"box-sizing":"border-box",
})
.val(value);
setTimeout(function(){
input.focus();
},100)
//submit new value on blur
input.on("change blur", function(e){
cell.trigger("editval", input.val());
});
//submit new value on enter
input.on("keydown", function(e){
if(e.keyCode == 13){
cell.trigger("editval", input.val());
}
});
return input;
},
number:function(cell, value){
//create and style input
var input = $("<input type='number'/>");
input.css({
"border":"1px",
"background":"transparent",
"padding":"4px",
"width":"100%",
"box-sizing":"border-box",
})
.val(value);
setTimeout(function(){
input.focus();
},100)
//submit new value on blur
input.on("blur", function(e){
cell.trigger("editval", input.val());
});
//submit new value on enter
input.on("keydown", function(e){
if(e.keyCode == 13){
cell.trigger("editval", input.val());
}
});
return input;
},
star:function(cell, value){
var maxStars = $("svg", cell).length;
var size = $("svg:first", cell).attr("width");
var stars=$("<div style='vertical-align:middle; padding:4px; display:inline-block; vertical-align:middle;'></div>");
value = parseInt(value) < maxStars ? parseInt(value) : maxStars;
var starActive = $('<svg width="' + size + '" height="' + size + '" class="tabulator-star-active" viewBox="0 0 512 512" xml:space="preserve" style="padding:0 1px;"><polygon fill="#488CE9" stroke="#014AAE" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>');
var starInactive = $('<svg width="' + size + '" height="' + size + '" class="tabulator-star-inactive" viewBox="0 0 512 512" xml:space="preserve" style="padding:0 1px;"><polygon fill="#010155" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/></svg>');
for(var i=1;i<= maxStars;i++){
var nextStar = i <= value ? starActive : starInactive;
stars.append(nextStar.clone());
}
//change number of active stars
var starChange = function(element){
if($(".tabulator-star-active", element.closest("div")).length != element.prevAll("svg").length + 1){
element.prevAll("svg").replaceWith(starActive.clone());
element.nextAll("svg").replaceWith(starInactive.clone());
element.replaceWith(starActive.clone());
}
}
stars.on("mouseover", "svg", function(e){
e.stopPropagation();
starChange($(this));
})
stars.on("mouseover", function(e){
$("svg", $(this)).replaceWith(starInactive.clone());
});
stars.on("click", function(e){
$(this).closest(".tabulator-cell").trigger("editval", 0);
});
stars.on("click", "svg", function(e){
var val = $(this).prevAll("svg").length + 1;
cell.trigger("editval", val);
});
cell.css({
"white-space": "nowrap",
"overflow": "hidden",
"text-overflow": "ellipsis",
})
cell.on("blur", function(){
$(this).trigger("editcancel");
});
//allow key based navigation
cell.on("keydown", function(e){
switch(e.keyCode){
case 39: //right arrow
starChange($(".tabulator-star-inactive:first", stars))
break;
case 37: //left arrow
var prevstar = $(".tabulator-star-active:last", stars).prev("svg")
if(prevstar.length){
starChange(prevstar)
}else{
$("svg", stars).replaceWith(starInactive.clone());
}
break;
case 13: //enter
cell.trigger("editval", $(".tabulator-star-active", stars).length);
break;
}
});
return stars;
},
progress:function(cell, value){
//set default parameters
var max = $("div", cell).data("max");
var min = $("div", cell).data("min");
//make sure value is in range
value = parseFloat(value) <= max ? parseFloat(value) : max;
value = parseFloat(value) >= min ? parseFloat(value) : min;
//workout percentage
var percent = (max - min) / 100;
value = 100 - Math.round((value - min) / percent);
cell.css({
padding:"0 4px",
});
var newVal = function(){
var newval = (percent * Math.round(bar.outerWidth() / (cell.width()/100))) + min;
cell.trigger("editval", newval);
}
var bar = $("<div style='position:absolute; top:8px; bottom:8px; left:4px; right:" + value + "%; margin-right:4px; background-color:#488CE9; display:inline-block; max-width:100%; min-width:0%;' data-max='" + max + "' data-min='" + min + "'></div>");
var handle = $("<div class='tabulator-progress-handle' style='position:absolute; right:0; top:0; bottom:0; width:5px;'></div>");
bar.append(handle);
handle.on("mousedown", function(e){
bar.data("mouseDrag", e.screenX);
bar.data("mouseDragWidth", bar.outerWidth());
})
handle.on("mouseover", function(){$(this).css({cursor:"ew-resize"})})
cell.on("mousemove", function(e){
if(bar.data("mouseDrag")){
bar.css({width: bar.data("mouseDragWidth") + (e.screenX - bar.data("mouseDrag"))})
}
})
cell.on("mouseup", function(e){
if(bar.data("mouseDrag")){
e.stopPropagation();
e.stopImmediatePropagation();
bar.data("mouseDragOut", true);
bar.data("mouseDrag", false);
bar.data("mouseDragWidth", false);
newVal();
}
});
//allow key based navigation
cell.on("keydown", function(e){
switch(e.keyCode){
case 39: //right arrow
bar.css({"width" : bar.width() + cell.width()/100});
break;
case 37: //left arrow
bar.css({"width" : bar.width() - cell.width()/100});
break;
case 13: //enter
newVal();
break;
}
});
cell.on("blur", function(){
$(this).trigger("editcancel");
});
return bar;
},
tickCross:function(cell, value){
//create and style input
var input = $("<input type='checkbox'/>");
input.css({
"border":"1px",
"background":"transparent",
"margin-top":"5px",
"box-sizing":"border-box",
})
.val(value);
setTimeout(function(){
input.focus();
},100)
if(value === true || value === 'true' || value === 'True' || value === 1){
input.prop("checked", true)
}else{
input.prop("checked", false)
}
//submit new value on blur
input.on("change blur", function(e){
cell.trigger("editval", input.is(":checked"));
});
//submit new value on enter
input.on("keydown", function(e){
if(e.keyCode == 13){
cell.trigger("editval", input.is(":checked"));
}
});
return input;
},
tick:function(cell, value){
//create and style input
var input = $("<input type='checkbox'/>");
input.css({
"border":"1px",
"background":"transparent",
"margin-top":"5px",
"box-sizing":"border-box",
})
.val(value);
setTimeout(function(){
input.focus();
},100)
if(value === true || value === 'true' || value === 'True' || value === 1){
input.prop("checked", true)
}else{
input.prop("checked", false)
}
//submit new value on blur
input.on("change blur", function(e){
cell.trigger("editval", input.is(":checked"));
});
//submit new value on enter
input.on("keydown", function(e){
if(e.keyCode == 13){
cell.trigger("editval", input.is(":checked"));
}
});
return input;
},
},
////////////////// Tabulator Desconstructor //////////////////
//deconstructor
_destroy: function() {
var self = this;
var element = self.element;
element.empty();
element.removeClass("tabulator");
},
});
})(); | updated rendering for tables with no height.
| tabulator.js | updated rendering for tables with no height. | <ide><path>abulator.js
<ide>
<ide> //set all headers to the same height
<ide> _vertAlignColHeaders:function(){
<del> var headerHeight = self.header.outerHeight()
<del>
<del> $(".tabulator-col, .tabulator-col-row-handle", self.header).css({"height":""}).css({"height":self.header.innerHeight() + "px"});
<del>
<del> if(self.options.height && headerHeight != self.header.outerHeight()){
<del> self.tableHolder.css({
<del> "min-height":"calc(100% - " + self.header.outerHeight() + "px)",
<del> "max-height":"calc(100% - " + self.header.outerHeight() + "px)",
<del> });
<add>
<add> if(self.header){
<add> var headerHeight = self.header.outerHeight()
<add>
<add> $(".tabulator-col, .tabulator-col-row-handle", self.header).css({"height":""}).css({"height":self.header.innerHeight() + "px"});
<add>
<add> if(self.options.height && headerHeight != self.header.outerHeight()){
<add> self.tableHolder.css({
<add> "min-height":"calc(100% - " + self.header.outerHeight() + "px)",
<add> "max-height":"calc(100% - " + self.header.outerHeight() + "px)",
<add> });
<add> }
<ide> }
<ide> },
<ide>
<ide> }
<ide> }
<ide>
<del> if(!self.options.height){
<del> var height = self.tableHolder.outerHeight() + self.header.outerHeight();
<del>
<del> if(self.footer){
<del> height += self.footer.outerHeight() + 1;
<del> }
<del>
<del> self.element.css({height:height})
<del> }
<add> // if(!self.options.height){
<add> // var height = self.tableHolder.outerHeight() + self.header.outerHeight();
<add>
<add> // if(self.footer){
<add> // height += self.footer.outerHeight() + 1;
<add> // }
<add>
<add> // // self.element.css({height:height})
<add> // }
<ide>
<ide> //resize cells vertically to fit row contents
<del> $(".tabulator-row", self.table).each(function(){
<del> $(".tabulator-cell, .tabulator-row-handle", $(this)).css({"height":$(this).outerHeight() + "px"});
<del> })
<add> if(self.element.is(":visible")){
<add> $(".tabulator-row", self.table).each(function(){
<add> $(".tabulator-cell, .tabulator-row-handle", $(this)).css({"height":$(this).outerHeight() + "px"});
<add> })
<add> }
<ide>
<ide> },
<ide> |
|
Java | apache-2.0 | 20f45a902347b0ab2a67345596d84882651fa6ea | 0 | cacristo/ceos-project | package org.jaexcel.framework.JAEX.engine;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jaexcel.framework.JAEX.annotation.XlsConfiguration;
import org.jaexcel.framework.JAEX.annotation.XlsDecorator;
import org.jaexcel.framework.JAEX.annotation.XlsDecorators;
import org.jaexcel.framework.JAEX.annotation.XlsElement;
import org.jaexcel.framework.JAEX.annotation.XlsNestedHeader;
import org.jaexcel.framework.JAEX.annotation.XlsSheet;
import org.jaexcel.framework.JAEX.configuration.Configuration;
import org.jaexcel.framework.JAEX.definition.ExceptionMessage;
import org.jaexcel.framework.JAEX.definition.ExtensionFileType;
import org.jaexcel.framework.JAEX.definition.PropagationType;
import org.jaexcel.framework.JAEX.exception.ConfigurationException;
import org.jaexcel.framework.JAEX.exception.ConverterException;
import org.jaexcel.framework.JAEX.exception.ElementException;
import org.jaexcel.framework.JAEX.exception.SheetException;
public class Engine implements IEngine {
// Workbook wb;
@Deprecated
Configuration configuration;
// CellDecorator headerDecorator;
// Map<String, CellStyle> stylesMap = new HashMap<String, CellStyle>();
// Map<String, CellDecorator> cellDecoratorMap = new HashMap<String,
// CellDecorator>();
/**
* Get the runtime class of the object passed as parameter.
*
* @param object
* the object
* @return the runtime class
* @throws ElementException
*/
private Class<?> initializeRuntimeClass(Object object) throws ElementException {
Class<?> oC = null;
try {
/* instance object class */
oC = object.getClass();
} catch (Exception e) {
throw new ElementException(ExceptionMessage.ElementException_NullObject.getMessage(), e);
}
return oC;
}
/**
* Initialize the configuration to apply at the Excel.
*
* @param oC
* the {@link Class<?>}
* @return
* @throws ConfigurationException
*/
private void initializeConfigurationData(ConfigCriteria configCriteria, Class<?> oC) throws ConfigurationException {
/* Process @XlsConfiguration */
if (oC.isAnnotationPresent(XlsConfiguration.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class);
initializeConfiguration(configCriteria, xlsAnnotation);
} else {
throw new ConfigurationException(
ExceptionMessage.ConfigurationException_XlsConfigurationMissing.getMessage());
}
/* Process @XlsSheet */
if (oC.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class);
initializeSheetConfiguration(configCriteria, xlsAnnotation);
} else {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_XlsSheetMissing.getMessage());
}
}
/**
* Add the main xls configuration.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param annotation
* the {@link XlsConfiguration}
* @return
*/
private void initializeConfiguration(ConfigCriteria configCriteria, XlsConfiguration annotation) {
configCriteria.setFileName(annotation.nameFile());
configCriteria.setCompleteFileName(annotation.nameFile() + annotation.extensionFile().getExtension());
configCriteria.setExtension(annotation.extensionFile());
}
/**
* Add the sheet configuration.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param annotation
* the {@link XlsSheet}
* @return
*/
private void initializeSheetConfiguration(ConfigCriteria configCriteria, XlsSheet annotation) {
configCriteria.setTitleSheet(annotation.title());
configCriteria.setPropagation(annotation.propagation());
configCriteria.setStartRow(annotation.startRow());
configCriteria.setStartCell(annotation.startCell());
}
/**
* Initialize the configuration to apply at the Excel.
*
* @param oC
* the {@link Class<?>}
* @return
*/
@Deprecated
private Configuration initializeConfigurationData(Class<?> oC) {
Configuration config = null;
/* Process @XlsConfiguration */
if (oC.isAnnotationPresent(XlsConfiguration.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class);
config = initializeConfiguration(xlsAnnotation);
}
/* Process @XlsSheet */
if (oC.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class);
config = initializeSheetConfiguration(xlsAnnotation);
}
return config;
}
/**
* Add the main xls configuration.
*
* @param config
* the {@link XlsConfiguration}
* @return
*/
@Deprecated
private Configuration initializeConfiguration(XlsConfiguration config) {
if (configuration == null) {
configuration = new Configuration();
}
configuration.setName(config.nameFile());
configuration.setNameFile(config.nameFile() + config.extensionFile().getExtension());
configuration.setExtensionFile(config.extensionFile());
return configuration;
}
/**
* Add the sheet configuration.
*
* @param config
* the {@link XlsSheet}
* @return
*/
@Deprecated
private Configuration initializeSheetConfiguration(XlsSheet config) {
if (configuration == null) {
configuration = new Configuration();
}
configuration.setTitleSheet(config.title());
configuration.setPropagationType(config.propagation());
configuration.setStartRow(config.startRow());
configuration.setStartCell(config.startCell());
return configuration;
}
/**
* Initialize Workbook.
*
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook}.
*/
private Workbook initializeWorkbook(ExtensionFileType type) {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook();
} else {
return new XSSFWorkbook();
}
}
/**
* Initialize Workbook from FileInputStream.
*
* @param inputStream
* the file input stream
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook} created
* @throws IOException
*/
private Workbook initializeWorkbook(FileInputStream inputStream, ExtensionFileType type) throws IOException {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook(inputStream);
} else {
return new XSSFWorkbook(inputStream);
}
}
/**
* Initialize Workbook from byte[].
*
* @param byteArray
* the array of bytes
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook} created
* @throws IOException
*/
private Workbook initializeWorkbook(byte[] byteArray, ExtensionFileType type) throws IOException {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook(new ByteArrayInputStream(byteArray));
} else {
return new XSSFWorkbook(new ByteArrayInputStream(byteArray));
}
}
/**
* Initialize Sheet.
*
* @param wb
* the {@link Workbook} to use
* @param sheetName
* the name of the sheet
* @return the {@link Sheet} created
* @throws SheetException
*/
private Sheet initializeSheet(Workbook wb, String sheetName) throws SheetException {
Sheet s = null;
try {
s = wb.createSheet(sheetName);
} catch (Exception e) {
throw new SheetException(ExceptionMessage.SheetException_CreationSheet.getMessage(), e);
}
return s;
}
/**
* Validate if the nested header configuration is valid.
*
* @param isPH
* true if propagation is HORIZONTAL otherwise false to
* propagation VERTICAL
* @param annotation
* the {@link XlsNestedHeader} annotation
* @throws ConfigurationException
*/
private void isValidNestedHeaderConfiguration(boolean isPH, XlsNestedHeader annotation)
throws ConfigurationException {
if (isPH && annotation.startX() == annotation.endX()) {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_Conflict.getMessage());
} else if (!isPH && annotation.startY() == annotation.endY()) {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_Conflict.getMessage());
}
}
/**
* Apply merge region if necessary.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param r
* the {@link Row}
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param isPH
* true if propagation horizontally, false if propagation
* vertically
*/
private void applyMergeRegion(ConfigCriteria configCriteria, Row r, int idxR, int idxC, boolean isPH)
throws Exception {
/* Process @XlsNestedHeader */
if (configCriteria.getField().isAnnotationPresent(XlsNestedHeader.class)) {
XlsNestedHeader annotation = (XlsNestedHeader) configCriteria.getField()
.getAnnotation(XlsNestedHeader.class);
/* if row null is necessary to create it */
if (r == null) {
r = initializeRow(configCriteria.getSheet(), idxR);
}
/* validation of configuration */
isValidNestedHeaderConfiguration(isPH, annotation);
/* prepare position rows / cells */
int startRow, endRow, startCell, endCell;
if (isPH) {
startRow = endRow = idxR;
startCell = idxC + annotation.startX();
endCell = idxC + annotation.endX();
} else {
startRow = idxR + annotation.startY();
endRow = idxR + annotation.endY();
startCell = endCell = idxC;
}
/* initialize master header cell */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), r, startCell, annotation.title());
/* merge region of the master header cell */
configCriteria.getSheet().addMergedRegion(new CellRangeAddress(startRow, endRow, startCell, endCell));
}
}
/**
* Initialize an row.
*
* @param s
* the {@link Sheet} to add the row
* @param idxR
* position of the new row
* @return the {@link Row} created
*/
private Row initializeRow(Sheet s, int idxR) {
return s.createRow(idxR);
}
/**
* Initialize an cell according the type of field and the PropagationType is
* PROPAGATION_HORIZONTAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return in case of the object return the number of cell created,
* otherwise 0
* @throws Exception
*/
private int initializeCellByFieldHorizontal(ConfigCriteria configCriteria, Object o, int idxR, int idxC, int cL)
throws Exception {
int counter = 0;
// FIXME uncomment line to activate cascade level
// if (cL <= configCriteria.getCascadeLevel().getCode()) {
/* make the field accessible to recover the value */
configCriteria.getField().setAccessible(true);
Class<?> fT = configCriteria.getField().getType();
boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);
if (!isAppliedObject && !fT.isPrimitive()) {
Object nO = configCriteria.getField().get(o);
/* manage null objects */
if (nO == null) {
nO = fT.newInstance();
}
Class<?> oC = nO.getClass();
counter = marshalAsPropagationHorizontal(configCriteria, nO, oC, idxR, idxC - 1, cL + 1);
}
// FIXME uncomment line to activate cascade level
// }
return counter;
}
/**
* Initialize an cell according the type of field and the PropagationType is
* PROPAGATION_VERTICAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param r
* the content row
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return
* @throws Exception
*/
private int initializeCellByFieldVertical(ConfigCriteria configCriteria, Object o, Row r, int idxR, int idxC,
int cL) throws Exception {
int counter = 0;
// FIXME uncomment line to activate cascade level
// if (cL <= configCriteria.getCascadeLevel().getCode()) {
/* make the field accessible to recover the value */
configCriteria.getField().setAccessible(true);
Class<?> fT = configCriteria.getField().getType();
configCriteria.setRow(r);
boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);
if (!isAppliedObject && !fT.isPrimitive()) {
Object nO = configCriteria.getField().get(o);
/* manage null objects */
if (nO == null) {
nO = fT.newInstance();
}
Class<?> oC = nO.getClass();
counter = marshalAsPropagationVertical(configCriteria, nO, oC, idxR - 1, idxC - 1, cL + 1);
}
// FIXME uncomment line to activate cascade level
// }
return counter;
}
/**
* Apply the base object to cell.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param fT
* the field type
* @param idxC
* the position of the cell
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws ConverterException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
private boolean toExcel(ConfigCriteria configCriteria, Object o, Class<?> fT, int idxC)
throws IllegalArgumentException, IllegalAccessException, ConverterException, NoSuchMethodException,
SecurityException, InvocationTargetException {
/* flag which define if the cell was updated or not */
boolean isUpdated = false;
/* initialize cell */
Cell cell = null;
switch (fT.getName()) {
case CellValueUtils.OBJECT_DATE:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toDate(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_STRING:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toString(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_INTEGER:
/* falls through */
case CellValueUtils.PRIMITIVE_INTEGER:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toInteger(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_LONG:
/* falls through */
case CellValueUtils.PRIMITIVE_LONG:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toLong(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_DOUBLE:
/* falls through */
case CellValueUtils.PRIMITIVE_DOUBLE:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toDouble(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_BIGDECIMAL:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toBigDecimal(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_FLOAT:
/* falls through */
case CellValueUtils.PRIMITIVE_FLOAT:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toFloat(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_BOOLEAN:
/* falls through */
case CellValueUtils.PRIMITIVE_BOOLEAN:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toBoolean(configCriteria, o, cell);
break;
default:
isUpdated = false;
break;
}
if (!isUpdated && fT.isEnum()) {
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toEnum(configCriteria, o, cell);
}
return isUpdated;
}
/**
* Apply the base object from cell.
*
* @param o
* the object
* @param fT
* the field type
* @param f
* the field
* @param c
* the cell
* @param xlsAnnotation
* the {@link XlsElement} annotation
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws ConverterException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private boolean toObject(Object o, Class<?> fT, Field f, Cell c, XlsElement xlsAnnotation)
throws IllegalArgumentException, IllegalAccessException, ConverterException {
/* flag which define if the cell was updated or not */
boolean isUpdated = false;
f.setAccessible(true);
switch (fT.getName()) {
case CellValueUtils.OBJECT_DATE:
// FIXME review the management
if (StringUtils.isBlank(xlsAnnotation.transformMask())) {
f.set(o, c.getDateCellValue());
} else {
String date = c.getStringCellValue();
if (StringUtils.isNotBlank(date)) {
String tM = xlsAnnotation.transformMask();
String fM = xlsAnnotation.formatMask();
String decorator = StringUtils.isEmpty(tM)
? (StringUtils.isEmpty(fM) ? CellStyleUtils.MASK_DECORATOR_DATE : fM) : tM;
SimpleDateFormat dt = new SimpleDateFormat(decorator);
try {
Date dateConverted = dt.parse(date);
f.set(o, dateConverted);
} catch (ParseException e) {
/*
* if date decorator do not match with a valid mask
* launch exception
*/
throw new ConverterException(ExceptionMessage.ConverterException_Date.getMessage(), e);
}
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_STRING:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, CellValueUtils.fromExcel(c));
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_INTEGER:
/* falls through */
case CellValueUtils.PRIMITIVE_INTEGER:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).intValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_LONG:
/* falls through */
case CellValueUtils.PRIMITIVE_LONG:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).longValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_DOUBLE:
/* falls through */
case CellValueUtils.PRIMITIVE_DOUBLE:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c).replace(",", ".")));
} else {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)));
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_BIGDECIMAL:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
f.set(o, BigDecimal.valueOf(Double.valueOf(CellValueUtils.fromExcel(c).replace(",", "."))));
} else {
f.set(o, BigDecimal.valueOf(Double.valueOf(CellValueUtils.fromExcel(c))));
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_FLOAT:
/* falls through */
case CellValueUtils.PRIMITIVE_FLOAT:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).floatValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_BOOLEAN:
/* falls through */
case CellValueUtils.PRIMITIVE_BOOLEAN:
String booleanValue = c.getStringCellValue();
if (StringUtils.isNotBlank(booleanValue)) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
/* apply format mask defined at transform mask */
String[] split = xlsAnnotation.transformMask().split("/");
f.set(o, StringUtils.isNotBlank(booleanValue) ? (split[0].equals(booleanValue) ? true : false)
: null);
} else {
/* locale mode */
f.set(o, StringUtils.isNotBlank(booleanValue) ? Boolean.valueOf(booleanValue) : null);
}
}
isUpdated = true;
break;
default:
isUpdated = false;
break;
}
if (!isUpdated && fT.isEnum()) {
if (StringUtils.isNotBlank(c.getStringCellValue())) {
f.set(o, Enum.valueOf((Class<Enum>) fT, c.getStringCellValue()));
}
isUpdated = true;
}
return isUpdated;
}
/**
* Convert the object to file with the PropagationType as
* PROPAGATION_HORIZONTAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return
* @throws IllegalAccessException
*/
private int marshalAsPropagationHorizontal(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR, int idxC,
int cL) throws Exception {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* update field at ConfigCriteria */
configCriteria.setField(f);
/* process each field from the object */
if (configCriteria.getRowHeader() != null) {
/* calculate index of the cell */
int tmpIdxRow = idxR - 3;
/* apply merge region */
applyMergeRegion(configCriteria, null, tmpIdxRow, idxC, true);
}
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/* update annotation at ConfigCriteria */
configCriteria.setElement(xlsAnnotation);
/* apply customized rules defined at the object */
if (StringUtils.isNotBlank(xlsAnnotation.customizedRules())) {
CellValueUtils.applyCustomizedRules(o, xlsAnnotation.customizedRules());
}
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
if (configCriteria.getRowHeader() != null) {
/* header treatment */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), configCriteria.getRowHeader(),
idxC + xlsAnnotation.position(), xlsAnnotation.title());
}
/* content treatment */
idxC += initializeCellByFieldHorizontal(configCriteria, o, idxR, idxC + xlsAnnotation.position(), cL);
}
}
return counter;
}
/**
* Convert the object to file with the PropagationType as
* PROPAGATION_VERTICAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return
* @throws Exception
*/
private int marshalAsPropagationVertical(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR, int idxC,
int cL) throws Exception {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* backup base index of the cell */
int baseIdxCell = idxC;
/* get declared fields */
List<Field> fieldList = Arrays.asList(oC.getDeclaredFields());
for (Field field : fieldList) {
/* process each field from the object */
configCriteria.setField(field);
/* restart the index of the cell */
idxC = baseIdxCell;
/* Process @XlsElement */
if (field.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) field.getAnnotation(XlsElement.class);
configCriteria.setElement(xlsAnnotation);
/* apply customized rules defined at the object */
if (StringUtils.isNotBlank(xlsAnnotation.customizedRules())) {
CellValueUtils.applyCustomizedRules(o, xlsAnnotation.customizedRules());
}
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* create the row */
Row row = null;
if (baseIdxCell == 1) {
int tmpIdxCell = idxC - 1;
/* initialize row */
row = initializeRow(configCriteria.getSheet(), idxR + xlsAnnotation.position());
/* apply merge region */
applyMergeRegion(configCriteria, row, idxR, tmpIdxCell, false);
/* header treatment */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), row, idxC,
xlsAnnotation.title());
} else {
row = configCriteria.getSheet().getRow(idxR + xlsAnnotation.position());
}
/* increment the cell position */
idxC++;
/* content treatment */
idxR += initializeCellByFieldVertical(configCriteria, o, row, idxR + xlsAnnotation.position(), idxC,
cL);
}
}
return counter;
}
/**
* Convert the file to object with the PropagationType as
* PROPAGATION_HORIZONTAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @return
* @throws IllegalAccessException
* @throws ConverterException
* @throws InstantiationException
*/
private int unmarshalAsPropagationHorizontal(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR,
int idxC) throws IllegalAccessException, ConverterException, InstantiationException {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* process each field from the object */
Class<?> fT = f.getType();
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* content row */
Row contentRow = configCriteria.getSheet().getRow(idxR + 1);
Cell contentCell = contentRow.getCell(idxC + xlsAnnotation.position());
boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation);
if (!isAppliedToBaseObject && !fT.isPrimitive()) {
Object subObjbect = fT.newInstance();
Class<?> subObjbectClass = subObjbect.getClass();
int internalCellCounter = unmarshalAsPropagationHorizontal(configCriteria, subObjbect,
subObjbectClass, idxR, idxC + xlsAnnotation.position() - 1);
/* add the sub object to the parent object */
f.set(o, subObjbect);
/* update the index */
idxC += internalCellCounter;
}
}
}
return counter;
}
/**
* Convert the file to object with the PropagationType as
* PROPAGATION_VERTICAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @return
* @throws IllegalAccessException
* @throws ConverterException
* @throws InstantiationException
*/
private int unmarshalAsPropagationVertical(ConfigCriteria configCriteria, Object object, Class<?> oC, int idxR,
int idxC) throws IllegalAccessException, ConverterException, InstantiationException {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* process each field from the object */
Class<?> fT = f.getType();
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* content row */
Row contentRow = configCriteria.getSheet().getRow(idxR + xlsAnnotation.position());
Cell contentCell = contentRow.getCell(idxC + 1);
boolean isAppliedToBaseObject = toObject(object, fT, f, contentCell, xlsAnnotation);
if (!isAppliedToBaseObject && !fT.isPrimitive()) {
Object subObjbect = fT.newInstance();
Class<?> subObjbectClass = subObjbect.getClass();
int internalCellCounter = unmarshalAsPropagationVertical(configCriteria, subObjbect,
subObjbectClass, idxR + xlsAnnotation.position() - 1, idxC);
/* add the sub object to the parent object */
f.set(object, subObjbect);
/* update the index */
idxR += internalCellCounter;
}
}
}
return counter;
}
/**
* Generate file output stream.
*
* @param wb
* the {@link Workbook}
* @param name
* the name
* @return
* @throws Exception
*/
private FileOutputStream workbookFileOutputStream(Workbook wb, String name) throws Exception {
FileOutputStream output = new FileOutputStream(name);
wb.write(output);
output.close();
return output;
}
/**
* Generate the byte array.
*
* @param wb
* the {@link Workbook}
* @return the byte[]
* @throws IOException
*/
private byte[] workbookToByteAray(Workbook wb) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
wb.write(bos);
} finally {
bos.close();
}
return bos.toByteArray();
}
/* ######################## engine methods ########################## */
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters.
*
* @param configCriteria
* the {@link ConfigCriteria} to use.
* @param object
* the object to apply at the workbook.
* @throws ElementException
* @throws ConfigurationException
* @throws SheetException
* @throws Exception
*/
private void marshalEngine(ConfigCriteria configCriteria, Object object)
throws ElementException, ConfigurationException, SheetException, Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
// ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* initialize Workbook */
configCriteria.setWorkbook(initializeWorkbook(configCriteria.getExtension()));
/* initialize style cell via annotations */
if (oC.isAnnotationPresent(XlsDecorators.class)) {
XlsDecorators xlsDecorators = (XlsDecorators) oC.getAnnotation(XlsDecorators.class);
for (XlsDecorator decorator : xlsDecorators.values()) {
configCriteria.getStylesMap().put(decorator.decoratorName(),
CellStyleUtils.initializeCellStyleByXlsDecorator(configCriteria.getWorkbook(), decorator));
}
}
/* initialize style cell via default option */
configCriteria.initializeCellDecorator();
// configCriteria.setStylesMap(stylesMap);
/* initialize Sheet */
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet()));
/* initialize Row & Cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
/* initialize rows according the PropagationType */
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
marshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell, 0);
} else {
marshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell, 0);
}
// FIXME apply the column size here - if necessary
}
/**
* Extract from the workbook based at the {@link ConfigCriteria} and the
* object passed as parameters.
*
* @param configCriteria
* the {@link ConfigCriteria} to use.
* @param object
* the object to apply at the workbook.
* @param oC
* the object class
* @throws Exception
*/
private void unmarshalEngine(ConfigCriteria configCriteria, Object object, Class<?> oC) throws Exception {
/* initialize sheet */
configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
/* initialize index row & cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
} else {
unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
}
}
/* ######################## Marshal methods ########################## */
/**
* Generate the sheet based at the object passed as parameter and return the
* sheet generated.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Sheet} generated
*/
public Sheet marshalToSheet(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Sheet generated */
return configCriteria.getWorkbook().getSheetAt(0);
}
/**
* Generate the sheet based at the {@link ConfigCriteria} and the object
* passed as parameters and return the sheet generated.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @return the {@link Sheet} generated
*/
public Sheet marshalToSheet(ConfigCriteria configCriteria, Object object) throws Exception {
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Sheet generated */
return configCriteria.getWorkbook().getSheetAt(0);
}
/**
* Generate the workbook based at the object passed as parameter and return
* the workbook generated.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public Workbook marshalToWorkbook(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Workbook generated */
return configCriteria.getWorkbook();
}
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters and return the workbook generated.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public Workbook marshalToWorkbook(ConfigCriteria configCriteria, Object object) throws Exception {
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Workbook generated */
return configCriteria.getWorkbook();
}
/**
* Generate the workbook from the object passed as parameter and return the
* respective {@link FileOutputStream}.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public byte[] marshalToByte(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/* Generate the byte array to return */
return workbookToByteAray(configCriteria.getWorkbook());
}
/**
* Generate the workbook based at the object passed as parameters and save
* it at the path send as parameter.
*
* @param object
* the object to apply at the workbook.
* @param pathFile
* the file path where will be the file saved
*/
public void marshalAndSave(Object object, String pathFile) throws Exception {
/* Generate the workbook from the object passed as parameter */
ConfigCriteria configCriteria = new ConfigCriteria();
marshalAndSave(configCriteria, object, pathFile);
}
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters and save it at the path send as parameter.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @param pathFile
* the file path where will be the file saved
*/
public void marshalAndSave(ConfigCriteria configCriteria, Object object, String pathFile) throws Exception {
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/*
* check if the path terminate with the file separator, otherwise will
* be added to avoid any problem
*/
if (!pathFile.endsWith(File.separator)) {
pathFile = pathFile.concat(File.separator);
}
/* Save the Workbook at a specified path (received as parameter) */
workbookFileOutputStream(configCriteria.getWorkbook(), pathFile + configCriteria.getCompleteFileName());
}
/**
* Generate the workbook from the collection of objects.
*
* @param collection
* the collection of objects to apply at the workbook.
* @param filename
* the file name
* @param extensionFileType
* the file extension
* @throws Exception
*/
public void marshalAsCollection(Collection<?> collection, final String filename,
final ExtensionFileType extensionFileType) throws Exception {
// Temos que iniciar o config data neste ponto porque
// como estamos na escritura de uma coleccao
// temos que ter o nome e a extensao antes de iniciar o excel
configuration = new Configuration();
configuration.setExtensionFile(extensionFileType);
configuration.setNameFile(filename);
Configuration config = configuration;
ConfigCriteria configCriteria = new ConfigCriteria();
configCriteria.setPropagation(config.getPropagationType());
configCriteria.setExtension(config.getExtensionFile());
// initialize Workbook
configCriteria.setWorkbook(initializeWorkbook(config.getExtensionFile()));
// initialize style cell via default option
configCriteria.initializeCellDecorator();
// configCriteria.setStylesMap(stylesMap);
int idxRow = 0, idxCell = 0, index = 0;
@SuppressWarnings("rawtypes")
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
// We get the class of the object
Class<?> objectClass = object.getClass();
// Process @XlsSheet
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) objectClass.getAnnotation(XlsSheet.class);
config = initializeSheetConfiguration(xlsAnnotation);
}
// initialize rows according the PropagationType
if (PropagationType.PROPAGATION_HORIZONTAL.equals(config.getPropagationType())) {
idxCell = config.getStartCell();
if (configCriteria.getWorkbook().getNumberOfSheets() == 0
|| configCriteria.getWorkbook().getSheet(config.getTitleSheet()) == null) {
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), config.getTitleSheet()));
idxRow = config.getStartRow();
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
} else {
idxRow = configCriteria.getSheet().getLastRowNum() + 1;
configCriteria.setRowHeader(null);
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
}
marshalAsPropagationHorizontal(configCriteria, object, objectClass, idxRow, idxCell, 0);
} else {
idxRow = config.getStartRow();
if (configCriteria.getWorkbook().getNumberOfSheets() == 0
|| configCriteria.getWorkbook().getSheet(config.getTitleSheet()) == null) {
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), config.getTitleSheet()));
idxCell = config.getStartCell();
} else {
idxCell = index + 1;
}
marshalAsPropagationVertical(configCriteria, object, objectClass, idxRow, idxCell, 0);
index = index + 1;
}
}
// FIXME manage return value
workbookFileOutputStream(configCriteria.getWorkbook(),
"D:\\projects\\" + config.getNameFile() + config.getExtensionFile().getExtension());
}
/* ######################## Unmarshal methods ######################## */
/**
* Generate the object from the workbook passed as parameter.
*
* @param object
* the object to fill up.
* @param workbook
* the {@link Workbook} to read and pass the information to the
* object
* @return the {@link Object} filled up
* @throws ConfigurationException
*/
public Object unmarshalFromWorkbook(Object object, Workbook workbook) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* set workbook */
configCriteria.setWorkbook(workbook);
/* Extract from the workbook to the object passed as parameter */
unmarshalEngine(configCriteria, object, oC);
return object;
}
/**
* Generate the object from the path file passed as parameter.
*
* @param object
* the object to fill up.
* @param pathFile
* the path where is found the file to read and pass the
* information to the object
* @return the {@link Object} filled up
*/
public Object unmarshalFromPath(Object object, String pathFile) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/*
* check if the path terminate with the file separator, otherwise will
* be added to avoid any problem
*/
if (!pathFile.endsWith(File.separator)) {
pathFile = pathFile.concat(File.separator);
}
FileInputStream input = new FileInputStream(pathFile + configCriteria.getCompleteFileName());
/* set workbook */
configCriteria.setWorkbook(initializeWorkbook(input, configCriteria.getExtension()));
/* Extract from the workbook to the object passed as parameter */
unmarshalEngine(configCriteria, object, oC);
return object;
}
/**
* Generate the object from the byte array passed as parameter.
*
* @param object
* the object to fill up.
* @param inputByte
* the byte array to read and pass the information to the object
* @return the {@link Object} filled up
*/
public Object unmarshalFromByte(Object object, byte[] byteArray) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* set workbook */
configCriteria.setWorkbook(initializeWorkbook(byteArray, configCriteria.getExtension()));
/* Extract from the workbook to the object passed as parameter */
unmarshalEngine(configCriteria, object, oC);
return object;
}
/**
* Manage the unmarshal internally.
*
* @param object
* the object to fill up.
* @param oC
* the obect class
* @param config
* the {@link Configuration} to use
* @param input
* the {@link FileInputStream} to use
* @throws IOException
* @throws IllegalAccessException
* @throws ConverterException
* @throws InstantiationException
* @throws SheetException
*/
private void unmarshalIntern(Object object, Class<?> oC, ConfigCriteria configCriteria, FileInputStream input)
throws IOException, IllegalAccessException, ConverterException, InstantiationException, SheetException {
configCriteria.setWorkbook(initializeWorkbook(input, configCriteria.getExtension()));
configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
// FIXME add manage sheet null
if (configCriteria.getSheet() == null) {
throw new SheetException(ExceptionMessage.SheetException_CreationSheet.getMessage());
}
/* initialize index row & cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
} else {
unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
}
}
@Override
public void marshalAsCollection(Collection<?> collection) {
// TODO Auto-generated method stub
}
@Override
public Collection<?> unmarshalToCollection(Object object) {
// TODO Auto-generated method stub
return null;
}
/* ############################################# */
/* ################## TO REVIEW ################ */
/* ############################################# */
/**
* marshal
*
* @throws Exception
*/
@Deprecated
public void marshal(Object object) throws Exception {
Class<?> objectClass = object.getClass();
ConfigCriteria configCriteria = new ConfigCriteria();
/* Process @XlsConfiguration */
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) objectClass.getAnnotation(XlsConfiguration.class);
initializeConfiguration(configCriteria, xlsAnnotation);
}
/* Process @XlsSheet */
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) objectClass.getAnnotation(XlsSheet.class);
initializeSheetConfiguration(configCriteria, xlsAnnotation);
}
/* initialize Workbook */
configCriteria.setWorkbook(initializeWorkbook(configCriteria.getExtension()));
/* initialize style cell via annotations */
if (objectClass.isAnnotationPresent(XlsDecorators.class)) {
XlsDecorators xlsDecorators = (XlsDecorators) objectClass.getAnnotation(XlsDecorators.class);
for (XlsDecorator decorator : xlsDecorators.values()) {
configCriteria.getStylesMap().put(decorator.decoratorName(),
CellStyleUtils.initializeCellStyleByXlsDecorator(configCriteria.getWorkbook(), decorator));
}
}
/* initialize style cell via default option */
configCriteria.initializeCellDecorator();
/* initialize Sheet */
// FIXME add loop if necessary
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet()));
/* initialize Row & Cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
/* initialize rows according the PropagationType */
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
marshalAsPropagationHorizontal(configCriteria, object, objectClass, idxRow, idxCell, 0);
} else {
marshalAsPropagationVertical(configCriteria, object, objectClass, idxRow, idxCell, 0);
}
// FIXME manage return value
workbookFileOutputStream(configCriteria.getWorkbook(), "D:\\projects\\" + configCriteria.getFileName());
}
@Deprecated
public Object unmarshal(Object object) throws IOException, IllegalArgumentException, IllegalAccessException,
ConverterException, InstantiationException, ElementException, SheetException {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
Configuration config = initializeConfigurationData(oC);
FileInputStream input = new FileInputStream("D:\\projects\\" + config.getNameFile());
unmarshalIntern(object, oC, new ConfigCriteria(), input);
return object;
}
/**
* Generate the workbook from the object passed as parameter and return the
* respective {@link FileOutputStream}.
*
* @param object
* the object to apply at the workbook.
* @return the {@link FileOutputStream} generated
*/
@Override
public FileOutputStream marshalToFileOutputStream(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/* Generate the FileOutputStream to return */
return workbookFileOutputStream(configCriteria.getWorkbook(), configCriteria.getFileName());
}
/**
* Generate the object from the {@link FileInputStream} passed as parameter.
*
* @param object
* the object to apply at the workbook.
* @param stream
* the {@link FileInputStream} to read
* @return the {@link Object} filled up
*/
@Override
public Object unmarshalFromFileInputStream(Object object, FileInputStream stream) throws Exception {
/* instance object class */
Class<?> oC = object.getClass();
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* set workbook */
configCriteria.setWorkbook(initializeWorkbook(stream, configCriteria.getExtension()));
unmarshalEngine(configCriteria, object, oC);
return object;
}
} | JAEX/src/main/java/org/jaexcel/framework/JAEX/engine/Engine.java | package org.jaexcel.framework.JAEX.engine;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jaexcel.framework.JAEX.annotation.XlsConfiguration;
import org.jaexcel.framework.JAEX.annotation.XlsDecorator;
import org.jaexcel.framework.JAEX.annotation.XlsDecorators;
import org.jaexcel.framework.JAEX.annotation.XlsElement;
import org.jaexcel.framework.JAEX.annotation.XlsNestedHeader;
import org.jaexcel.framework.JAEX.annotation.XlsSheet;
import org.jaexcel.framework.JAEX.configuration.Configuration;
import org.jaexcel.framework.JAEX.definition.ExceptionMessage;
import org.jaexcel.framework.JAEX.definition.ExtensionFileType;
import org.jaexcel.framework.JAEX.definition.PropagationType;
import org.jaexcel.framework.JAEX.exception.ConfigurationException;
import org.jaexcel.framework.JAEX.exception.ConverterException;
import org.jaexcel.framework.JAEX.exception.ElementException;
import org.jaexcel.framework.JAEX.exception.SheetException;
public class Engine implements IEngine {
// Workbook wb;
@Deprecated
Configuration configuration;
// CellDecorator headerDecorator;
// Map<String, CellStyle> stylesMap = new HashMap<String, CellStyle>();
// Map<String, CellDecorator> cellDecoratorMap = new HashMap<String,
// CellDecorator>();
/**
* Get the runtime class of the object passed as parameter.
*
* @param object
* the object
* @return the runtime class
* @throws ElementException
*/
private Class<?> initializeRuntimeClass(Object object) throws ElementException {
Class<?> oC = null;
try {
/* instance object class */
oC = object.getClass();
} catch (Exception e) {
throw new ElementException(ExceptionMessage.ElementException_NullObject.getMessage(), e);
}
return oC;
}
/**
* Initialize the configuration to apply at the Excel.
*
* @param oC
* the {@link Class<?>}
* @return
* @throws ConfigurationException
*/
private void initializeConfigurationData(ConfigCriteria configCriteria, Class<?> oC) throws ConfigurationException {
/* Process @XlsConfiguration */
if (oC.isAnnotationPresent(XlsConfiguration.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class);
initializeConfiguration(configCriteria, xlsAnnotation);
} else {
throw new ConfigurationException(
ExceptionMessage.ConfigurationException_XlsConfigurationMissing.getMessage());
}
/* Process @XlsSheet */
if (oC.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class);
initializeSheetConfiguration(configCriteria, xlsAnnotation);
} else {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_XlsSheetMissing.getMessage());
}
}
/**
* Add the main xls configuration.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param annotation
* the {@link XlsConfiguration}
* @return
*/
private void initializeConfiguration(ConfigCriteria configCriteria, XlsConfiguration annotation) {
configCriteria.setFileName(annotation.nameFile());
configCriteria.setCompleteFileName(annotation.nameFile() + annotation.extensionFile().getExtension());
configCriteria.setExtension(annotation.extensionFile());
}
/**
* Add the sheet configuration.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param annotation
* the {@link XlsSheet}
* @return
*/
private void initializeSheetConfiguration(ConfigCriteria configCriteria, XlsSheet annotation) {
configCriteria.setTitleSheet(annotation.title());
configCriteria.setPropagation(annotation.propagation());
configCriteria.setStartRow(annotation.startRow());
configCriteria.setStartCell(annotation.startCell());
}
/**
* Initialize the configuration to apply at the Excel.
*
* @param oC
* the {@link Class<?>}
* @return
*/
@Deprecated
private Configuration initializeConfigurationData(Class<?> oC) {
Configuration config = null;
/* Process @XlsConfiguration */
if (oC.isAnnotationPresent(XlsConfiguration.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class);
config = initializeConfiguration(xlsAnnotation);
}
/* Process @XlsSheet */
if (oC.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class);
config = initializeSheetConfiguration(xlsAnnotation);
}
return config;
}
/**
* Add the main xls configuration.
*
* @param config
* the {@link XlsConfiguration}
* @return
*/
@Deprecated
private Configuration initializeConfiguration(XlsConfiguration config) {
if (configuration == null) {
configuration = new Configuration();
}
configuration.setName(config.nameFile());
configuration.setNameFile(config.nameFile() + config.extensionFile().getExtension());
configuration.setExtensionFile(config.extensionFile());
return configuration;
}
/**
* Add the sheet configuration.
*
* @param config
* the {@link XlsSheet}
* @return
*/
@Deprecated
private Configuration initializeSheetConfiguration(XlsSheet config) {
if (configuration == null) {
configuration = new Configuration();
}
configuration.setTitleSheet(config.title());
configuration.setPropagationType(config.propagation());
configuration.setStartRow(config.startRow());
configuration.setStartCell(config.startCell());
return configuration;
}
/**
* Initialize Workbook.
*
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook}.
*/
private Workbook initializeWorkbook(ExtensionFileType type) {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook();
} else {
return new XSSFWorkbook();
}
}
/**
* Initialize Workbook from FileInputStream.
*
* @param inputStream
* the file input stream
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook} created
* @throws IOException
*/
private Workbook initializeWorkbook(FileInputStream inputStream, ExtensionFileType type) throws IOException {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook(inputStream);
} else {
return new XSSFWorkbook(inputStream);
}
}
/**
* Initialize Workbook from byte[].
*
* @param byteArray
* the array of bytes
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook} created
* @throws IOException
*/
private Workbook initializeWorkbook(byte[] byteArray, ExtensionFileType type) throws IOException {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook(new ByteArrayInputStream(byteArray));
} else {
return new XSSFWorkbook(new ByteArrayInputStream(byteArray));
}
}
/**
* Initialize Sheet.
*
* @param wb
* the {@link Workbook} to use
* @param sheetName
* the name of the sheet
* @return the {@link Sheet} created
* @throws SheetException
*/
private Sheet initializeSheet(Workbook wb, String sheetName) throws SheetException {
Sheet s = null;
try {
s = wb.createSheet(sheetName);
} catch (Exception e) {
throw new SheetException(ExceptionMessage.SheetException_CreationSheet.getMessage(), e);
}
return s;
}
/**
* Validate if the nested header configuration is valid.
*
* @param isPH
* true if propagation is HORIZONTAL otherwise false to
* propagation VERTICAL
* @param annotation
* the {@link XlsNestedHeader} annotation
* @throws ConfigurationException
*/
private void isValidNestedHeaderConfiguration(boolean isPH, XlsNestedHeader annotation)
throws ConfigurationException {
if (isPH && annotation.startX() == annotation.endX()) {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_Conflict.getMessage());
} else if (!isPH && annotation.startY() == annotation.endY()) {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_Conflict.getMessage());
}
}
/**
* Apply merge region if necessary.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param r
* the {@link Row}
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param isPH
* true if propagation horizontally, false if propagation
* vertically
*/
private void applyMergeRegion(ConfigCriteria configCriteria, Row r, int idxR, int idxC, boolean isPH)
throws Exception {
/* Process @XlsNestedHeader */
if (configCriteria.getField().isAnnotationPresent(XlsNestedHeader.class)) {
XlsNestedHeader annotation = (XlsNestedHeader) configCriteria.getField()
.getAnnotation(XlsNestedHeader.class);
/* if row null is necessary to create it */
if (r == null) {
r = initializeRow(configCriteria.getSheet(), idxR);
}
/* validation of configuration */
isValidNestedHeaderConfiguration(isPH, annotation);
/* prepare position rows / cells */
int startRow, endRow, startCell, endCell;
if (isPH) {
startRow = endRow = idxR;
startCell = idxC + annotation.startX();
endCell = idxC + annotation.endX();
} else {
startRow = idxR + annotation.startY();
endRow = idxR + annotation.endY();
startCell = endCell = idxC;
}
/* initialize master header cell */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), r, startCell, annotation.title());
/* merge region of the master header cell */
configCriteria.getSheet().addMergedRegion(new CellRangeAddress(startRow, endRow, startCell, endCell));
}
}
/**
* Initialize an row.
*
* @param s
* the {@link Sheet} to add the row
* @param idxR
* position of the new row
* @return the {@link Row} created
*/
private Row initializeRow(Sheet s, int idxR) {
return s.createRow(idxR);
}
/**
* Initialize an cell according the type of field and the PropagationType is
* PROPAGATION_HORIZONTAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return in case of the object return the number of cell created,
* otherwise 0
* @throws Exception
*/
private int initializeCellByFieldHorizontal(ConfigCriteria configCriteria, Object o, int idxR, int idxC, int cL)
throws Exception {
int counter = 0;
// FIXME uncomment line to activate cascade level
// if (cL <= configCriteria.getCascadeLevel().getCode()) {
/* make the field accessible to recover the value */
configCriteria.getField().setAccessible(true);
Class<?> fT = configCriteria.getField().getType();
boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);
if (!isAppliedObject && !fT.isPrimitive()) {
Object nO = configCriteria.getField().get(o);
/* manage null objects */
if (nO == null) {
nO = fT.newInstance();
}
Class<?> oC = nO.getClass();
counter = marshalAsPropagationHorizontal(configCriteria, nO, oC, idxR, idxC - 1, cL + 1);
}
// FIXME uncomment line to activate cascade level
// }
return counter;
}
/**
* Initialize an cell according the type of field and the PropagationType is
* PROPAGATION_VERTICAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param r
* the content row
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return
* @throws Exception
*/
private int initializeCellByFieldVertical(ConfigCriteria configCriteria, Object o, Row r, int idxR, int idxC,
int cL) throws Exception {
int counter = 0;
// FIXME uncomment line to activate cascade level
// if (cL <= configCriteria.getCascadeLevel().getCode()) {
/* make the field accessible to recover the value */
configCriteria.getField().setAccessible(true);
Class<?> fT = configCriteria.getField().getType();
configCriteria.setRow(r);
boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);
if (!isAppliedObject && !fT.isPrimitive()) {
Object nO = configCriteria.getField().get(o);
/* manage null objects */
if (nO == null) {
nO = fT.newInstance();
}
Class<?> oC = nO.getClass();
counter = marshalAsPropagationVertical(configCriteria, nO, oC, idxR - 1, idxC - 1, cL + 1);
}
// FIXME uncomment line to activate cascade level
// }
return counter;
}
/**
* Apply the base object to cell.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param fT
* the field type
* @param idxC
* the position of the cell
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws ConverterException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
private boolean toExcel(ConfigCriteria configCriteria, Object o, Class<?> fT, int idxC)
throws IllegalArgumentException, IllegalAccessException, ConverterException, NoSuchMethodException,
SecurityException, InvocationTargetException {
/* flag which define if the cell was updated or not */
boolean isUpdated = false;
/* initialize cell */
Cell cell = null;
switch (fT.getName()) {
case CellValueUtils.OBJECT_DATE:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toDate(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_STRING:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toString(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_INTEGER:
/* falls through */
case CellValueUtils.PRIMITIVE_INTEGER:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toInteger(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_LONG:
/* falls through */
case CellValueUtils.PRIMITIVE_LONG:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toLong(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_DOUBLE:
/* falls through */
case CellValueUtils.PRIMITIVE_DOUBLE:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toDouble(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_BIGDECIMAL:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toBigDecimal(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_FLOAT:
/* falls through */
case CellValueUtils.PRIMITIVE_FLOAT:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toFloat(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_BOOLEAN:
/* falls through */
case CellValueUtils.PRIMITIVE_BOOLEAN:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toBoolean(configCriteria, o, cell);
break;
default:
isUpdated = false;
break;
}
if (!isUpdated && fT.isEnum()) {
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toEnum(configCriteria, o, cell);
}
return isUpdated;
}
/**
* Apply the base object from cell.
*
* @param o
* the object
* @param fT
* the field type
* @param f
* the field
* @param c
* the cell
* @param xlsAnnotation
* the {@link XlsElement} annotation
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws ConverterException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private boolean toObject(Object o, Class<?> fT, Field f, Cell c, XlsElement xlsAnnotation)
throws IllegalArgumentException, IllegalAccessException, ConverterException {
/* flag which define if the cell was updated or not */
boolean isUpdated = false;
f.setAccessible(true);
switch (fT.getName()) {
case CellValueUtils.OBJECT_DATE:
// FIXME review the management
if (StringUtils.isBlank(xlsAnnotation.transformMask())) {
f.set(o, c.getDateCellValue());
} else {
String date = c.getStringCellValue();
if (StringUtils.isNotBlank(date)) {
String tM = xlsAnnotation.transformMask();
String fM = xlsAnnotation.formatMask();
String decorator = StringUtils.isEmpty(tM)
? (StringUtils.isEmpty(fM) ? CellStyleUtils.MASK_DECORATOR_DATE : fM) : tM;
SimpleDateFormat dt = new SimpleDateFormat(decorator);
try {
Date dateConverted = dt.parse(date);
f.set(o, dateConverted);
} catch (ParseException e) {
/*
* if date decorator do not match with a valid mask
* launch exception
*/
throw new ConverterException(ExceptionMessage.ConverterException_Date.getMessage(), e);
}
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_STRING:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, CellValueUtils.fromExcel(c));
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_INTEGER:
/* falls through */
case CellValueUtils.PRIMITIVE_INTEGER:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).intValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_LONG:
/* falls through */
case CellValueUtils.PRIMITIVE_LONG:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).longValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_DOUBLE:
/* falls through */
case CellValueUtils.PRIMITIVE_DOUBLE:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c).replace(",", ".")));
} else {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)));
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_BIGDECIMAL:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
f.set(o, BigDecimal.valueOf(Double.valueOf(CellValueUtils.fromExcel(c).replace(",", "."))));
} else {
f.set(o, BigDecimal.valueOf(Double.valueOf(CellValueUtils.fromExcel(c))));
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_FLOAT:
/* falls through */
case CellValueUtils.PRIMITIVE_FLOAT:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).floatValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_BOOLEAN:
/* falls through */
case CellValueUtils.PRIMITIVE_BOOLEAN:
String booleanValue = c.getStringCellValue();
if (StringUtils.isNotBlank(booleanValue)) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
/* apply format mask defined at transform mask */
String[] split = xlsAnnotation.transformMask().split("/");
f.set(o, StringUtils.isNotBlank(booleanValue) ? (split[0].equals(booleanValue) ? true : false)
: null);
} else {
/* locale mode */
f.set(o, StringUtils.isNotBlank(booleanValue) ? Boolean.valueOf(booleanValue) : null);
}
}
isUpdated = true;
break;
default:
isUpdated = false;
break;
}
if (!isUpdated && fT.isEnum()) {
if (StringUtils.isNotBlank(c.getStringCellValue())) {
f.set(o, Enum.valueOf((Class<Enum>) fT, c.getStringCellValue()));
}
isUpdated = true;
}
return isUpdated;
}
/**
* Convert the object to file with the PropagationType as
* PROPAGATION_HORIZONTAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return
* @throws IllegalAccessException
*/
private int marshalAsPropagationHorizontal(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR, int idxC,
int cL) throws Exception {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* update field at ConfigCriteria */
configCriteria.setField(f);
/* process each field from the object */
if (configCriteria.getRowHeader() != null) {
/* calculate index of the cell */
int tmpIdxRow = idxR - 3;
/* apply merge region */
applyMergeRegion(configCriteria, null, tmpIdxRow, idxC, true);
}
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/* update annotation at ConfigCriteria */
configCriteria.setElement(xlsAnnotation);
/* apply customized rules defined at the object */
if (StringUtils.isNotBlank(xlsAnnotation.customizedRules())) {
CellValueUtils.applyCustomizedRules(o, xlsAnnotation.customizedRules());
}
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
if (configCriteria.getRowHeader() != null) {
/* header treatment */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), configCriteria.getRowHeader(),
idxC + xlsAnnotation.position(), xlsAnnotation.title());
}
/* content treatment */
idxC += initializeCellByFieldHorizontal(configCriteria, o, idxR, idxC + xlsAnnotation.position(), cL);
}
}
return counter;
}
/**
* Convert the object to file with the PropagationType as
* PROPAGATION_VERTICAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return
* @throws Exception
*/
private int marshalAsPropagationVertical(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR, int idxC,
int cL) throws Exception {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* backup base index of the cell */
int baseIdxCell = idxC;
/* get declared fields */
List<Field> fieldList = Arrays.asList(oC.getDeclaredFields());
for (Field field : fieldList) {
/* process each field from the object */
configCriteria.setField(field);
/* restart the index of the cell */
idxC = baseIdxCell;
/* Process @XlsElement */
if (field.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) field.getAnnotation(XlsElement.class);
configCriteria.setElement(xlsAnnotation);
/* apply customized rules defined at the object */
if (StringUtils.isNotBlank(xlsAnnotation.customizedRules())) {
CellValueUtils.applyCustomizedRules(o, xlsAnnotation.customizedRules());
}
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* create the row */
Row row = null;
if (baseIdxCell == 1) {
int tmpIdxCell = idxC - 1;
/* initialize row */
row = initializeRow(configCriteria.getSheet(), idxR + xlsAnnotation.position());
/* apply merge region */
applyMergeRegion(configCriteria, row, idxR, tmpIdxCell, false);
/* header treatment */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), row, idxC,
xlsAnnotation.title());
} else {
row = configCriteria.getSheet().getRow(idxR + xlsAnnotation.position());
}
/* increment the cell position */
idxC++;
/* content treatment */
idxR += initializeCellByFieldVertical(configCriteria, o, row, idxR + xlsAnnotation.position(), idxC,
cL);
}
}
return counter;
}
/**
* Convert the file to object with the PropagationType as
* PROPAGATION_HORIZONTAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @return
* @throws IllegalAccessException
* @throws ConverterException
* @throws InstantiationException
*/
private int unmarshalAsPropagationHorizontal(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR,
int idxC) throws IllegalAccessException, ConverterException, InstantiationException {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* process each field from the object */
Class<?> fT = f.getType();
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* content row */
Row contentRow = configCriteria.getSheet().getRow(idxR + 1);
Cell contentCell = contentRow.getCell(idxC + xlsAnnotation.position());
boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation);
if (!isAppliedToBaseObject && !fT.isPrimitive()) {
Object subObjbect = fT.newInstance();
Class<?> subObjbectClass = subObjbect.getClass();
int internalCellCounter = unmarshalAsPropagationHorizontal(configCriteria, subObjbect,
subObjbectClass, idxR, idxC + xlsAnnotation.position() - 1);
/* add the sub object to the parent object */
f.set(o, subObjbect);
/* update the index */
idxC += internalCellCounter;
}
}
}
return counter;
}
/**
* Convert the file to object with the PropagationType as
* PROPAGATION_VERTICAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @return
* @throws IllegalAccessException
* @throws ConverterException
* @throws InstantiationException
*/
private int unmarshalAsPropagationVertical(ConfigCriteria configCriteria, Object object, Class<?> oC, int idxR,
int idxC) throws IllegalAccessException, ConverterException, InstantiationException {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* process each field from the object */
Class<?> fT = f.getType();
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* content row */
Row contentRow = configCriteria.getSheet().getRow(idxR + xlsAnnotation.position());
Cell contentCell = contentRow.getCell(idxC + 1);
boolean isAppliedToBaseObject = toObject(object, fT, f, contentCell, xlsAnnotation);
if (!isAppliedToBaseObject && !fT.isPrimitive()) {
Object subObjbect = fT.newInstance();
Class<?> subObjbectClass = subObjbect.getClass();
int internalCellCounter = unmarshalAsPropagationVertical(configCriteria, subObjbect,
subObjbectClass, idxR + xlsAnnotation.position() - 1, idxC);
/* add the sub object to the parent object */
f.set(object, subObjbect);
/* update the index */
idxR += internalCellCounter;
}
}
}
return counter;
}
/**
* Generate file output stream.
*
* @param wb
* the {@link Workbook}
* @param name
* the name
* @return
* @throws Exception
*/
private FileOutputStream workbookFileOutputStream(Workbook wb, String name) throws Exception {
FileOutputStream output = new FileOutputStream(name);
wb.write(output);
output.close();
return output;
}
/**
* Generate the byte array.
*
* @param wb
* the {@link Workbook}
* @return the byte[]
* @throws IOException
*/
private byte[] workbookToByteAray(Workbook wb) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
wb.write(bos);
} finally {
bos.close();
}
return bos.toByteArray();
}
/* ######################## engine methods ########################## */
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters.
*
* @param configCriteria
* the {@link ConfigCriteria} to use.
* @param object
* the object to apply at the workbook.
* @throws ElementException
* @throws ConfigurationException
* @throws SheetException
* @throws Exception
*/
private void marshalEngine(ConfigCriteria configCriteria, Object object)
throws ElementException, ConfigurationException, SheetException, Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
// ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* initialize Workbook */
configCriteria.setWorkbook(initializeWorkbook(configCriteria.getExtension()));
/* initialize style cell via annotations */
if (oC.isAnnotationPresent(XlsDecorators.class)) {
XlsDecorators xlsDecorators = (XlsDecorators) oC.getAnnotation(XlsDecorators.class);
for (XlsDecorator decorator : xlsDecorators.values()) {
configCriteria.getStylesMap().put(decorator.decoratorName(),
CellStyleUtils.initializeCellStyleByXlsDecorator(configCriteria.getWorkbook(), decorator));
}
}
/* initialize style cell via default option */
configCriteria.initializeCellDecorator();
// configCriteria.setStylesMap(stylesMap);
/* initialize Sheet */
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet()));
/* initialize Row & Cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
/* initialize rows according the PropagationType */
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
marshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell, 0);
} else {
marshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell, 0);
}
// FIXME apply the column size here - if necessary
}
/* ######################## Marshal methods ########################## */
/**
* Generate the sheet based at the object passed as parameter and return the
* sheet generated.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Sheet} generated
*/
public Sheet marshalToSheet(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Sheet generated */
return configCriteria.getWorkbook().getSheetAt(0);
}
/**
* Generate the sheet based at the {@link ConfigCriteria} and the object
* passed as parameters and return the sheet generated.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @return the {@link Sheet} generated
*/
public Sheet marshalToSheet(ConfigCriteria configCriteria, Object object) throws Exception {
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Sheet generated */
return configCriteria.getWorkbook().getSheetAt(0);
}
/**
* Generate the workbook based at the object passed as parameter and return
* the workbook generated.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public Workbook marshalToWorkbook(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Workbook generated */
return configCriteria.getWorkbook();
}
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters and return the workbook generated.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public Workbook marshalToWorkbook(ConfigCriteria configCriteria, Object object) throws Exception {
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Workbook generated */
return configCriteria.getWorkbook();
}
/**
* Generate the workbook from the object passed as parameter and return the
* respective {@link FileOutputStream}.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public byte[] marshalToByte(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/* Generate the byte array to return */
return workbookToByteAray(configCriteria.getWorkbook());
}
/**
* Generate the workbook based at the object passed as parameters and save
* it at the path send as parameter.
*
* @param object
* the object to apply at the workbook.
* @param pathFile
* the file path where will be the file saved
*/
public void marshalAndSave(Object object, String pathFile) throws Exception {
/* Generate the workbook from the object passed as parameter */
ConfigCriteria configCriteria = new ConfigCriteria();
marshalAndSave(configCriteria, object, pathFile);
}
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters and save it at the path send as parameter.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @param pathFile
* the file path where will be the file saved
*/
public void marshalAndSave(ConfigCriteria configCriteria, Object object, String pathFile) throws Exception {
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/*
* check if the path terminate with the file separator, otherwise will
* be added to avoid any problem
*/
if (!pathFile.endsWith(File.separator)) {
pathFile = pathFile.concat(File.separator);
}
/* Save the Workbook at a specified path (received as parameter) */
workbookFileOutputStream(configCriteria.getWorkbook(), pathFile + configCriteria.getCompleteFileName());
}
/**
* Generate the workbook from the collection of objects.
*
* @param collection
* the collection of objects to apply at the workbook.
* @param filename
* the file name
* @param extensionFileType
* the file extension
* @throws Exception
*/
public void marshalAsCollection(Collection<?> collection, final String filename,
final ExtensionFileType extensionFileType) throws Exception {
// Temos que iniciar o config data neste ponto porque
// como estamos na escritura de uma coleccao
// temos que ter o nome e a extensao antes de iniciar o excel
configuration = new Configuration();
configuration.setExtensionFile(extensionFileType);
configuration.setNameFile(filename);
Configuration config = configuration;
ConfigCriteria configCriteria = new ConfigCriteria();
configCriteria.setPropagation(config.getPropagationType());
configCriteria.setExtension(config.getExtensionFile());
// initialize Workbook
configCriteria.setWorkbook(initializeWorkbook(config.getExtensionFile()));
// initialize style cell via default option
configCriteria.initializeCellDecorator();
// configCriteria.setStylesMap(stylesMap);
int idxRow = 0, idxCell = 0, index = 0;
@SuppressWarnings("rawtypes")
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
// We get the class of the object
Class<?> objectClass = object.getClass();
// Process @XlsSheet
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) objectClass.getAnnotation(XlsSheet.class);
config = initializeSheetConfiguration(xlsAnnotation);
}
// initialize rows according the PropagationType
if (PropagationType.PROPAGATION_HORIZONTAL.equals(config.getPropagationType())) {
idxCell = config.getStartCell();
if (configCriteria.getWorkbook().getNumberOfSheets() == 0
|| configCriteria.getWorkbook().getSheet(config.getTitleSheet()) == null) {
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), config.getTitleSheet()));
idxRow = config.getStartRow();
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
} else {
idxRow = configCriteria.getSheet().getLastRowNum() + 1;
configCriteria.setRowHeader(null);
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
}
marshalAsPropagationHorizontal(configCriteria, object, objectClass, idxRow, idxCell, 0);
} else {
idxRow = config.getStartRow();
if (configCriteria.getWorkbook().getNumberOfSheets() == 0
|| configCriteria.getWorkbook().getSheet(config.getTitleSheet()) == null) {
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), config.getTitleSheet()));
idxCell = config.getStartCell();
} else {
idxCell = index + 1;
}
marshalAsPropagationVertical(configCriteria, object, objectClass, idxRow, idxCell, 0);
index = index + 1;
}
}
// FIXME manage return value
workbookFileOutputStream(configCriteria.getWorkbook(),
"D:\\projects\\" + config.getNameFile() + config.getExtensionFile().getExtension());
}
/* ######################## Unmarshal methods ######################## */
/**
* Generate the object from the workbook passed as parameter.
*
* @param object
* the object to fill up.
* @param workbook
* the {@link Workbook} to read and pass the information to the
* object
* @return the {@link Object} filled up
* @throws ConfigurationException
*/
public Object unmarshalFromWorkbook(Object object, Workbook workbook) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
configCriteria.setWorkbook(workbook);
configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
/* initialize index row & cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
} else {
unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
}
return object;
}
/**
* Generate the object from the path file passed as parameter.
*
* @param object
* the object to fill up.
* @param pathFile
* the path where is found the file to read and pass the
* information to the object
* @return the {@link Object} filled up
*/
public Object unmarshalFromPath(Object object, String pathFile) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/*
* check if the path terminate with the file separator, otherwise will
* be added to avoid any problem
*/
if (!pathFile.endsWith(File.separator)) {
pathFile = pathFile.concat(File.separator);
}
FileInputStream input = new FileInputStream(pathFile + configCriteria.getCompleteFileName());
unmarshalIntern(object, oC, configCriteria, input);
return object;
}
/**
* Generate the object from the byte array passed as parameter.
*
* @param object
* the object to fill up.
* @param inputByte
* the byte array to read and pass the information to the object
* @return the {@link Object} filled up
*/
public Object unmarshalFromByte(Object object, byte[] byteArray) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
configCriteria.setWorkbook(initializeWorkbook(byteArray, configCriteria.getExtension()));
configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
/* initialize index row & cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
} else {
unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
}
return object;
}
/**
* Manage the unmarshal internally.
*
* @param object
* the object to fill up.
* @param oC
* the obect class
* @param config
* the {@link Configuration} to use
* @param input
* the {@link FileInputStream} to use
* @throws IOException
* @throws IllegalAccessException
* @throws ConverterException
* @throws InstantiationException
* @throws SheetException
*/
private void unmarshalIntern(Object object, Class<?> oC, ConfigCriteria configCriteria, FileInputStream input)
throws IOException, IllegalAccessException, ConverterException, InstantiationException, SheetException {
configCriteria.setWorkbook(initializeWorkbook(input, configCriteria.getExtension()));
configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
// FIXME add manage sheet null
if (configCriteria.getSheet() == null) {
throw new SheetException(ExceptionMessage.SheetException_CreationSheet.getMessage());
}
/* initialize index row & cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
} else {
unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
}
}
@Override
public void marshalAsCollection(Collection<?> collection) {
// TODO Auto-generated method stub
}
@Override
public Collection<?> unmarshalToCollection(Object object) {
// TODO Auto-generated method stub
return null;
}
/* ############################################# */
/* ################## TO REVIEW ################ */
/* ############################################# */
/**
* marshal
*
* @throws Exception
*/
@Deprecated
public void marshal(Object object) throws Exception {
Class<?> objectClass = object.getClass();
ConfigCriteria configCriteria = new ConfigCriteria();
/* Process @XlsConfiguration */
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) objectClass.getAnnotation(XlsConfiguration.class);
initializeConfiguration(configCriteria, xlsAnnotation);
}
/* Process @XlsSheet */
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) objectClass.getAnnotation(XlsSheet.class);
initializeSheetConfiguration(configCriteria, xlsAnnotation);
}
/* initialize Workbook */
configCriteria.setWorkbook(initializeWorkbook(configCriteria.getExtension()));
/* initialize style cell via annotations */
if (objectClass.isAnnotationPresent(XlsDecorators.class)) {
XlsDecorators xlsDecorators = (XlsDecorators) objectClass.getAnnotation(XlsDecorators.class);
for (XlsDecorator decorator : xlsDecorators.values()) {
configCriteria.getStylesMap().put(decorator.decoratorName(),
CellStyleUtils.initializeCellStyleByXlsDecorator(configCriteria.getWorkbook(), decorator));
}
}
/* initialize style cell via default option */
configCriteria.initializeCellDecorator();
/* initialize Sheet */
// FIXME add loop if necessary
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet()));
/* initialize Row & Cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
/* initialize rows according the PropagationType */
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
marshalAsPropagationHorizontal(configCriteria, object, objectClass, idxRow, idxCell, 0);
} else {
marshalAsPropagationVertical(configCriteria, object, objectClass, idxRow, idxCell, 0);
}
// FIXME manage return value
workbookFileOutputStream(configCriteria.getWorkbook(), "D:\\projects\\" + configCriteria.getFileName());
}
@Deprecated
public Object unmarshal(Object object) throws IOException, IllegalArgumentException, IllegalAccessException,
ConverterException, InstantiationException, ElementException, SheetException {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
Configuration config = initializeConfigurationData(oC);
FileInputStream input = new FileInputStream("D:\\projects\\" + config.getNameFile());
unmarshalIntern(object, oC, new ConfigCriteria(), input);
return object;
}
/**
* Generate the workbook from the object passed as parameter and return the
* respective {@link FileOutputStream}.
*
* @return the {@link Workbook} generated
*/
@Override
public FileOutputStream marshalToFileOutputStream(Object object) throws Exception {
/* Generate the workbook from the object passed as parameter */
Workbook wb = marshalToWorkbook(object);
/* Generate the FileOutputStream to return */
return workbookFileOutputStream(wb, configuration.getNameFile());
}
@Override
public Object unmarshalFromFileInputStream(Object object, FileInputStream stream)
throws IOException, IllegalArgumentException, IllegalAccessException, ConverterException,
InstantiationException, SheetException {
/* instance object class */
Class<?> oC = object.getClass();
ConfigCriteria configCriteria = new ConfigCriteria();
/* Process @XlsConfiguration */
if (oC.isAnnotationPresent(XlsConfiguration.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class);
initializeConfiguration(configCriteria, xlsAnnotation);
}
/* Process @XlsSheet */
if (oC.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class);
initializeSheetConfiguration(configCriteria, xlsAnnotation);
}
unmarshalIntern(object, oC, configCriteria, stream);
return object;
}
} | Refactor unmarshalEngine | JAEX/src/main/java/org/jaexcel/framework/JAEX/engine/Engine.java | Refactor unmarshalEngine | <ide><path>AEX/src/main/java/org/jaexcel/framework/JAEX/engine/Engine.java
<ide> // FIXME apply the column size here - if necessary
<ide> }
<ide>
<add> /**
<add> * Extract from the workbook based at the {@link ConfigCriteria} and the
<add> * object passed as parameters.
<add> *
<add> * @param configCriteria
<add> * the {@link ConfigCriteria} to use.
<add> * @param object
<add> * the object to apply at the workbook.
<add> * @param oC
<add> * the object class
<add> * @throws Exception
<add> */
<add> private void unmarshalEngine(ConfigCriteria configCriteria, Object object, Class<?> oC) throws Exception {
<add> /* initialize sheet */
<add> configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
<add>
<add> /* initialize index row & cell */
<add> int idxRow = configCriteria.getStartRow();
<add> int idxCell = configCriteria.getStartCell();
<add>
<add> if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
<add> unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
<add> } else {
<add> unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
<add> }
<add> }
<add>
<ide> /* ######################## Marshal methods ########################## */
<ide>
<ide> /**
<ide> ConfigCriteria configCriteria = new ConfigCriteria();
<ide> initializeConfigurationData(configCriteria, oC);
<ide>
<add> /* set workbook */
<ide> configCriteria.setWorkbook(workbook);
<del> configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
<del>
<del> /* initialize index row & cell */
<del> int idxRow = configCriteria.getStartRow();
<del> int idxCell = configCriteria.getStartCell();
<del>
<del> if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
<del> unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
<del> } else {
<del> unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
<del> }
<add>
<add> /* Extract from the workbook to the object passed as parameter */
<add> unmarshalEngine(configCriteria, object, oC);
<ide>
<ide> return object;
<ide> }
<ide> }
<ide>
<ide> FileInputStream input = new FileInputStream(pathFile + configCriteria.getCompleteFileName());
<del> unmarshalIntern(object, oC, configCriteria, input);
<add>
<add> /* set workbook */
<add> configCriteria.setWorkbook(initializeWorkbook(input, configCriteria.getExtension()));
<add>
<add> /* Extract from the workbook to the object passed as parameter */
<add> unmarshalEngine(configCriteria, object, oC);
<ide>
<ide> return object;
<ide> }
<ide> ConfigCriteria configCriteria = new ConfigCriteria();
<ide> initializeConfigurationData(configCriteria, oC);
<ide>
<add> /* set workbook */
<ide> configCriteria.setWorkbook(initializeWorkbook(byteArray, configCriteria.getExtension()));
<del> configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
<del>
<del> /* initialize index row & cell */
<del> int idxRow = configCriteria.getStartRow();
<del> int idxCell = configCriteria.getStartCell();
<del>
<del> if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
<del> unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
<del> } else {
<del> unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
<del> }
<add>
<add> /* Extract from the workbook to the object passed as parameter */
<add> unmarshalEngine(configCriteria, object, oC);
<ide>
<ide> return object;
<ide> }
<ide> * Generate the workbook from the object passed as parameter and return the
<ide> * respective {@link FileOutputStream}.
<ide> *
<del> * @return the {@link Workbook} generated
<add> * @param object
<add> * the object to apply at the workbook.
<add> * @return the {@link FileOutputStream} generated
<ide> */
<ide> @Override
<ide> public FileOutputStream marshalToFileOutputStream(Object object) throws Exception {
<add> /* Initialize a basic ConfigCriteria */
<add> ConfigCriteria configCriteria = new ConfigCriteria();
<add>
<ide> /* Generate the workbook from the object passed as parameter */
<del> Workbook wb = marshalToWorkbook(object);
<add> marshalEngine(configCriteria, object);
<ide>
<ide> /* Generate the FileOutputStream to return */
<del> return workbookFileOutputStream(wb, configuration.getNameFile());
<del> }
<del>
<add> return workbookFileOutputStream(configCriteria.getWorkbook(), configCriteria.getFileName());
<add> }
<add>
<add> /**
<add> * Generate the object from the {@link FileInputStream} passed as parameter.
<add> *
<add> * @param object
<add> * the object to apply at the workbook.
<add> * @param stream
<add> * the {@link FileInputStream} to read
<add> * @return the {@link Object} filled up
<add> */
<ide> @Override
<del> public Object unmarshalFromFileInputStream(Object object, FileInputStream stream)
<del> throws IOException, IllegalArgumentException, IllegalAccessException, ConverterException,
<del> InstantiationException, SheetException {
<add> public Object unmarshalFromFileInputStream(Object object, FileInputStream stream) throws Exception {
<ide> /* instance object class */
<ide> Class<?> oC = object.getClass();
<add>
<add> /* initialize configuration data */
<ide> ConfigCriteria configCriteria = new ConfigCriteria();
<del>
<del> /* Process @XlsConfiguration */
<del> if (oC.isAnnotationPresent(XlsConfiguration.class)) {
<del> XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class);
<del> initializeConfiguration(configCriteria, xlsAnnotation);
<del> }
<del>
<del> /* Process @XlsSheet */
<del> if (oC.isAnnotationPresent(XlsSheet.class)) {
<del> XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class);
<del> initializeSheetConfiguration(configCriteria, xlsAnnotation);
<del> }
<del>
<del> unmarshalIntern(object, oC, configCriteria, stream);
<add> initializeConfigurationData(configCriteria, oC);
<add>
<add> /* set workbook */
<add> configCriteria.setWorkbook(initializeWorkbook(stream, configCriteria.getExtension()));
<add>
<add> unmarshalEngine(configCriteria, object, oC);
<ide>
<ide> return object;
<ide> } |
|
Java | apache-2.0 | f4eff7d6c60aee4eeaefe48ded7b55a9d362b03e | 0 | apache/tapestry3,apache/tapestry3,apache/tapestry3,apache/tapestry3 | /*
* Tapestry Web Application Framework
* Copyright (c) 2002 by Howard Lewis Ship
*
* mailto:[email protected]
*
* This library is free software.
*
* You may redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation.
*
* Version 2.1 of the license should be included with this distribution in
* the file LICENSE, as well as License.html. If the license is not
* included with this distribution, you may find a copy at the FSF web
* site at 'www.gnu.org' or 'www.fsf.org', or you may write to the
* Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package tutorial.workbench.chart;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import com.jrefinery.chart.ChartFactory;
import com.jrefinery.chart.JFreeChart;
import com.jrefinery.data.DefaultPieDataset;
import com.primix.tapestry.BasePage;
import com.primix.tapestry.IAsset;
import com.primix.tapestry.IRequestCycle;
import com.primix.tapestry.IResponseWriter;
import com.primix.tapestry.RequestCycleException;
import com.primix.tapestry.Tapestry;
import com.primix.tapestry.valid.IValidationDelegate;
/**
* Demonstrates more complex form handling (including loops and dynamic addition/deletion of
* rows) as well as dynamic image generation using {@link JFreeChart}.
*
* @author Howard Lewis Ship
* @version $Id$
* @since 1.0.10
*
**/
public class Chart extends BasePage implements IChartProvider
{
private List plotValues;
private List removeValues;
private PlotValue plotValue;
public void detach()
{
plotValues = null;
removeValues = null;
plotValue = null;
super.detach();
}
/**
* Invokes {@link #getValues()}, which ensures that (on the very first request cycle),
* the persistent values property is set <em>before</em> the page recorder is locked.
*
**/
public void beginResponse(IResponseWriter writer, IRequestCycle cycle)
throws RequestCycleException
{
getPlotValues();
}
public List getPlotValues()
{
if (plotValues == null)
{
setPlotValues(new ArrayList());
plotValues.add(new PlotValue("Fred", 10));
plotValues.add(new PlotValue("Barney", 15));
plotValues.add(new PlotValue("Dino", 7));
}
return plotValues;
}
public void setPlotValues(List plotValues)
{
this.plotValues = plotValues;
fireObservedChange("plotValues", plotValues);
}
public PlotValue getPlotValue()
{
return plotValue;
}
public void setPlotValue(PlotValue plotValue)
{
this.plotValue = plotValue;
}
/**
* Invoked during the render; always returns false.
*
**/
public boolean isMarkedForDeletion()
{
return false;
}
/**
* Invoked by the deleted checkbox (for each plotValue). If true,
* the the current plotValue is added to the list of plotValues to
* remove (though the actual removing is done inside {@link #delete(IRequestCycle)},
* after the loop.
*
**/
public void setMarkedForDeletion(boolean value)
{
if (value)
{
if (removeValues == null)
removeValues = new ArrayList();
removeValues.add(plotValue);
// Deleting things screws up the validation delegate.
// That's because the errors are associated with the form name
// (not the component id), and deleting elements causes
// all the names to shift.
IValidationDelegate delegate = (IValidationDelegate)getBeans().getBean("delegate");
delegate.clear();
}
}
/**
* Form listener method; does nothing since we want to stay on this page.
*
**/
public void submit(IRequestCycle cycle)
{
}
/**
* Listener method for the add button, adds an additional (blank) plot value.
*
**/
public void add(IRequestCycle cycle)
{
plotValues.add(new PlotValue());
}
/**
* Listener method for the remove button, removes any checked plot values.
*
* @see #setMarkedForDeletion(boolean)
*
**/
public void delete(IRequestCycle cycle)
{
if (removeValues != null)
plotValues.removeAll(removeValues);
}
private IAsset chartImageAsset;
public IAsset getChartImageAsset()
{
if (chartImageAsset == null)
chartImageAsset = new ChartAsset(getRequestCycle(), this);
return chartImageAsset;
}
/**
* This method is invoked by the service (in a seperate request cycle from all the form handling stuff).
* The {@link #getChartImageAsset()} method provides an {@link IAsset} that is handled by the
* {@link ChartService}, and the asset encodes the identity of this page.
*
**/
public JFreeChart getChart()
{
DefaultPieDataset data = new DefaultPieDataset();
int count = plotValues.size();
for (int i = 0; i < count; i++)
{
PlotValue pv = (PlotValue)plotValues.get(i);
String name = pv.getName();
if (Tapestry.isNull(name))
name = "<New>";
data.setValue(name, new Integer(pv.getValue()));
}
JFreeChart result = ChartFactory.createPieChart("Pie Chart", data, false);
result.setBackgroundPaint(Color.decode("#ffffcc"));
return result;
}
}
| examples/Tutorial/src/tutorial/workbench/chart/Chart.java | /*
* Tapestry Web Application Framework
* Copyright (c) 2002 by Howard Lewis Ship
*
* mailto:[email protected]
*
* This library is free software.
*
* You may redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation.
*
* Version 2.1 of the license should be included with this distribution in
* the file LICENSE, as well as License.html. If the license is not
* included with this distribution, you may find a copy at the FSF web
* site at 'www.gnu.org' or 'www.fsf.org', or you may write to the
* Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package tutorial.workbench.chart;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import com.jrefinery.chart.ChartFactory;
import com.jrefinery.chart.JFreeChart;
import com.jrefinery.data.DefaultPieDataset;
import com.primix.tapestry.BasePage;
import com.primix.tapestry.IAsset;
import com.primix.tapestry.IRequestCycle;
import com.primix.tapestry.IResponseWriter;
import com.primix.tapestry.RequestCycleException;
import com.primix.tapestry.Tapestry;
import com.primix.tapestry.valid.IValidationDelegate;
/**
* Demonstrates more complex form handling (including loops and dynamic addition/deletion of
* rows) as well as dynamic image generation using {@link JFreeChart}.
*
* @author Howard Lewis Ship
* @version $Id$
* @since 1.0.10
*
**/
public class Chart extends BasePage implements IChartProvider
{
private List plotValues;
private List removeValues;
private PlotValue plotValue;
public void detach()
{
plotValues = null;
removeValues = null;
plotValue = null;
super.detach();
}
/**
* Invokes {@link #getValues()}, which ensures that (on the very first request cycle),
* the persistent values property is set <em>before</em> the page recorder is locked.
*
**/
public void beginResponse(IResponseWriter writer, IRequestCycle cycle)
throws RequestCycleException
{
getPlotValues();
}
public List getPlotValues()
{
if (plotValues == null)
{
setPlotValues(new ArrayList());
plotValues.add(new PlotValue("<New>", 0));
}
return plotValues;
}
public void setPlotValues(List plotValues)
{
this.plotValues = plotValues;
fireObservedChange("plotValues", plotValues);
}
public PlotValue getPlotValue()
{
return plotValue;
}
public void setPlotValue(PlotValue plotValue)
{
this.plotValue = plotValue;
}
/**
* Invoked during the render; always returns false.
*
**/
public boolean isMarkedForDeletion()
{
return false;
}
/**
* Invoked by the deleted checkbox (for each plotValue). If true,
* the the current plotValue is added to the list of plotValues to
* remove (though the actual removing is done inside {@link #delete(IRequestCycle)},
* after the loop.
*
**/
public void setMarkedForDeletion(boolean value)
{
if (value)
{
if (removeValues == null)
removeValues = new ArrayList();
removeValues.add(plotValue);
// Deleting things screws up the validation delegate.
// That's because the errors are associated with the form name
// (not the component id), and deleting elements causes
// all the names to shift.
IValidationDelegate delegate = (IValidationDelegate)getBeans().getBean("delegate");
delegate.clear();
}
}
/**
* Form listener method; does nothing since we want to stay on this page.
*
**/
public void submit(IRequestCycle cycle)
{
}
/**
* Listener method for the add button, adds an additional (blank) plot value.
*
**/
public void add(IRequestCycle cycle)
{
plotValues.add(new PlotValue());
}
/**
* Listener method for the remove button, removes any checked plot values.
*
* @see #setMarkedForDeletion(boolean)
*
**/
public void delete(IRequestCycle cycle)
{
if (removeValues != null)
plotValues.removeAll(removeValues);
}
private IAsset chartImageAsset;
public IAsset getChartImageAsset()
{
if (chartImageAsset == null)
chartImageAsset = new ChartAsset(getRequestCycle(), this);
return chartImageAsset;
}
/**
* This method is invoked by the service (in a seperate request cycle from all the form handling stuff).
* The {@link #getChartImageAsset()} method provides an {@link IAsset} that is handled by the
* {@link ChartService}, and the asset encodes the identity of this page.
*
**/
public JFreeChart getChart()
{
DefaultPieDataset data = new DefaultPieDataset();
int count = plotValues.size();
for (int i = 0; i < count; i++)
{
PlotValue pv = (PlotValue)plotValues.get(i);
String name = pv.getName();
if (Tapestry.isNull(name))
name = "<New>";
data.setValue(name, new Integer(pv.getValue()));
}
JFreeChart result = ChartFactory.createPieChart("Pie Chart", data, false);
result.setBackgroundPaint(Color.decode("#ffffcc"));
return result;
}
}
| Add default values to Chart, so first look shows a real Pie Chart.
git-svn-id: 1006245cb1bdea2fd4c9095e50bc2ef3d167b18c@242469 13f79535-47bb-0310-9956-ffa450edef68
| examples/Tutorial/src/tutorial/workbench/chart/Chart.java | Add default values to Chart, so first look shows a real Pie Chart. | <ide><path>xamples/Tutorial/src/tutorial/workbench/chart/Chart.java
<ide> {
<ide> setPlotValues(new ArrayList());
<ide>
<del> plotValues.add(new PlotValue("<New>", 0));
<add> plotValues.add(new PlotValue("Fred", 10));
<add> plotValues.add(new PlotValue("Barney", 15));
<add> plotValues.add(new PlotValue("Dino", 7));
<ide> }
<ide>
<ide> return plotValues; |
|
Java | apache-2.0 | b3c8a22c451587379959f4a697e98a283bf3c5ed | 0 | Ardulink/Ardulink-2,Ardulink/Ardulink-2,Ardulink/Ardulink-2 | /**
Copyright 2013 project Ardulink http://www.ardulink.org/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.ardulink.core.events;
import static java.util.Collections.unmodifiableSet;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* [ardulinktitle] [ardulinkversion]
*
* project Ardulink http://www.ardulink.org/
*
* [adsense]
*
*/
public class DefaultRplyEvent implements RplyEvent {
private final boolean ok;
private final long id;
private final Map<String, Object> parameters;
private final Set<String> names;
public DefaultRplyEvent(boolean ok, long id, Map<String, Object> parameters) {
this.ok = ok;
this.id = id;
this.parameters = parameters;
this.names = unmodifiableSet(parameters.keySet());
}
@Override
public boolean isOk() {
return ok;
}
@Override
public long getId() {
return id;
}
@Override
public Set<String> getParameterNames() {
return names;
}
@Override
public Object getParameterValue(String name) {
return parameters.get(name);
}
}
| ardulink-core-base/src/main/java/org/ardulink/core/events/DefaultRplyEvent.java | /**
Copyright 2013 project Ardulink http://www.ardulink.org/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.ardulink.core.events;
import java.util.Map;
import java.util.Set;
/**
* [ardulinktitle] [ardulinkversion]
*
* project Ardulink http://www.ardulink.org/
*
* [adsense]
*
*/
public class DefaultRplyEvent implements RplyEvent {
private final boolean ok;
private final long id;
private final Map<String, Object> parameters;
public DefaultRplyEvent(boolean ok, long id, Map<String, Object> parameters) {
this.ok = ok;
this.id = id;
this.parameters = parameters;
}
@Override
public boolean isOk() {
return ok;
}
@Override
public long getId() {
return id;
}
@Override
public Set<String> getParameterNames() {
return parameters.keySet();
}
@Override
public Object getParameterValue(String name) {
return parameters.get(name);
}
}
| house keeping
| ardulink-core-base/src/main/java/org/ardulink/core/events/DefaultRplyEvent.java | house keeping | <ide><path>rdulink-core-base/src/main/java/org/ardulink/core/events/DefaultRplyEvent.java
<ide>
<ide> package org.ardulink.core.events;
<ide>
<add>import static java.util.Collections.unmodifiableSet;
<add>
<add>import java.util.Collections;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<ide> private final boolean ok;
<ide> private final long id;
<ide> private final Map<String, Object> parameters;
<add> private final Set<String> names;
<ide>
<ide> public DefaultRplyEvent(boolean ok, long id, Map<String, Object> parameters) {
<ide> this.ok = ok;
<ide> this.id = id;
<ide> this.parameters = parameters;
<add> this.names = unmodifiableSet(parameters.keySet());
<ide> }
<ide>
<ide> @Override
<ide>
<ide> @Override
<ide> public Set<String> getParameterNames() {
<del> return parameters.keySet();
<add> return names;
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 1afa2faff891b4539ceda1ac252dc5857736dad1 | 0 | wiperdog/wiperdog,wiperdog/wiperdog | package org.wiperdog.installer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.wiperdog.installer.internal.InstallerUtil;
import org.wiperdog.installer.internal.InstallerXML;
import org.wiperdog.installer.internal.XMLErrorHandler;
import java.text.SimpleDateFormat;
/**
* Self-extractor main class of the installer, it help to peform all major tasks of the installation
* such as: Self-extracting, run groovy for pre-configure.
* @author nguyenvannghia
* Email: [email protected]
*/
public class SelfExtractorCmd {
public static String OUTPUT_FOLDER = "";
public static final String LOG_FILE_NAME = System.getProperty("user.dir")+"/WiperdogInstaller.log";
public static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.S");
public static File loggingFile = new File(LOG_FILE_NAME);
public static FileOutputStream fo = null;
static void printInfoLog(String content) throws Exception{
if(fo == null)
fo = new FileOutputStream(loggingFile, true);
fo.write((content+ "\n").getBytes());
System.out.println(content);
}
public static void fileInfoLog(String content) throws Exception{
if(fo == null)
fo = new FileOutputStream(loggingFile, true);
fo.write((content+ "\n").getBytes());
}
public static void main(String args[]) throws Exception{
try {
// Create a new log file for each time user run the installer
fo = new FileOutputStream(loggingFile);
String beginMessage = "Start the Wiperdog installation at " + df.format(new java.util.Date(System.currentTimeMillis())) + "\n";
fo.write(beginMessage.getBytes());
fo.flush();
fo.close();
fo = null;
} catch (Exception e) {
e.printStackTrace();
}
//Argurments : -d (wiperdog home) ,-j(netty port),-r (restful server port),-m(mongodb host),-p(mongodb port),-n(database name),-u(user database),-pw(password database),-mp(mail policy),-s(install as OS service)
// -jd (job directory ) , -id (instances directory) , -cd (jobclass directory)
List<String> listParams = new ArrayList<String>();
listParams.add("-d");
listParams.add("-j");
listParams.add("-r");
listParams.add("-m");
listParams.add("-jd");
listParams.add("-id");
listParams.add("-td");
listParams.add("-cd");
listParams.add("-p");
listParams.add("-n");
listParams.add("-u");
listParams.add("-pw");
listParams.add("-mp");
listParams.add("-s");
listParams.add("-ni");
List<String> listArgs = Arrays.asList(args);
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader inp = new BufferedReader(converter, 512);
try {
try{
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
public void run(){
try{
printInfoLog("Installer shutdown...");
}catch(Exception exx){
//Ignore exception for shutdown hook.
}
}
}));
}catch(Exception ex){
// In case CTRL + C were pressed
Thread.currentThread().sleep(100);
}
// check command syntax to configure OUTPUT_FOLDER
if (args.length == 0 || containParam(args, "-ni")) {
if(args.length == 0){
printInfoLog("Press CTRL+C to quit. You can execute default installation with -ni option");
}
//Get current dir
String currentDir = System.getProperty("user.dir");
//Get jar file name, create install directory name
String jarFileName = new java.io.File(SelfExtractorCmd.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
String wiperdogDirName = "";
if (jarFileName.endsWith(".jar")) {
wiperdogDirName = jarFileName.substring(0, jarFileName.length() - 4);
}
if (wiperdogDirName.endsWith("-unix")) {
wiperdogDirName = wiperdogDirName.substring(0, wiperdogDirName.length() - 5);
}
if (wiperdogDirName.endsWith("-win")) {
wiperdogDirName = wiperdogDirName.substring(0, wiperdogDirName.length() - 4);
}
if (wiperdogDirName == "") {
wiperdogDirName = "wiperdogHome";
}
//wiperdog home path
String wiperdogPath = currentDir + File.separator + wiperdogDirName;
//Check install or not
String confirmStr = "";
if(containParam(args, "-ni")){
if(containParam(args, "-d")){
OUTPUT_FOLDER = getParamValue(args, "-d");
}else
OUTPUT_FOLDER = wiperdogPath;
}else{
while (confirmStr!=null && (!confirmStr.toLowerCase().equalsIgnoreCase("y") && !confirmStr.toLowerCase().equalsIgnoreCase("n"))) {
printInfoLog("Do you want to install wiperdog at " + wiperdogPath + " ? [y/n] :");
confirmStr = inp.readLine().trim();
if (confirmStr.toLowerCase().equalsIgnoreCase("y")) {
OUTPUT_FOLDER = wiperdogPath;
} else if (confirmStr.toLowerCase().equalsIgnoreCase("n")) {
System.exit(0);
}
}
}
} else if ((args.length < 2 && !containParam(args,"-ni")) || (!args[0].trim().equals("-d") && !containParam(args,"-ni")) ) {
printInfoLog("Wrong parameter. Usage:\n \t\t java -jar [Installer Jar] \n \t\t or \n \t\t java -jar [Installer Jar] -d [INSTALL_PATH>] \n \t\t or \n \t\t java -jar [Installer Jar] -d [INSTALL_PATH] -j [nettyport] -m [mongodb host] -p [mongodb port] -n [mongodb database name] -u [mongodb user name] -pw [mongodb password] -mp [mail policy] -s [yes/no install as OS service] \n \t\t or \n \t\t java -jar [Installer Jar] -ni [ -d INSTALL_PATH] [-j nettyport] ... ]");
System.exit(0);
}else {
if(containParam(args,"-d"))
OUTPUT_FOLDER = (String) args[1];
}// end if (args.length ==0 || -ni option)
//Prepare arguments for Groovy script running
String strArgs = "";
//Pass all arguments to Groovy class
for(int i = 0; i< args.length; i++ ){
//Get netty port from argurment
if(args[i].equals("-j")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
if( isNumeric(args[i+1])){
strArgs += "-j " + args[i+1] + " ";
i++;
} else {
printInfoLog( "Netty port must be number: " + args[i]);
return;
}
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get restful server port from argurment
if(args[i].equals("-r")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
if( isNumeric(args[i+1])){
strArgs += "-r " + args[i+1] + " ";
i++;
} else {
printInfoLog( "Restful server port must be numeric: " + args[i]);
return;
}
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
// Get job directory from argurment
if (args[i].equals("-jd")) {
if ((args.length > i + 1) && (args[i + 1].trim() != "") && (!listParams.contains(args[i + 1].trim()))) {
strArgs += "-jd " + args[i + 1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
// Get intances directory from argurment
if (args[i].equals("-id")) {
if ((args.length > i + 1) && (args[i + 1].trim() != "") && (!listParams.contains(args[i + 1].trim()))) {
strArgs += "-id " + args[i + 1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
// Get job class directory from argurment
if (args[i].equals("-cd")) {
if ((args.length > i + 1) && (args[i + 1].trim() != "") && (!listParams.contains(args[i + 1].trim()))) {
strArgs += "-cd " + args[i + 1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
// Get trigger directory from argurment
if (args[i].equals("-td")) {
if ((args.length > i + 1) && (args[i + 1].trim() != "") && (!listParams.contains(args[i + 1].trim()))) {
strArgs += "-td " + args[i + 1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get Mongodb Host from argurment
if(args[i].equals("-m")) {
if(( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-m " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get Mongodb Port from argurment
if(args[i].equals("-p")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
if(isNumeric(args[i+1])){
strArgs += "-p " + args[i+1] + " ";
i++;
} else {
printInfoLog("Mongodb port must be number: " + args[i]);
return;
}
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get Mongodb database name from argurment
if(args[i].equals("-n")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-n " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get user connect to database
if(args[i].equals("-u")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-u " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get password connect to database
//String pattern = "[a-zA-Z0-9]+";
if(args[i].equals("-pw")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim())) ){
strArgs += "-pw " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get mail send to policy
if(args[i].equals("-mp")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-mp " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get install wiperdog as service
if(args[i].equals("-s")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-s " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get -ni option
if(args[i].equals("-ni")) {
strArgs += args[i] + " ";
}
}
File outputDir = new File(OUTPUT_FOLDER);
//check if wiperdog home params is not an absolute path
if(!outputDir.isAbsolute()) {
String userDir = System.getProperty("user.dir");
OUTPUT_FOLDER = new File (userDir, OUTPUT_FOLDER).getAbsolutePath();
}
printInfoLog("Wiperdog will be install to directory: "
+ OUTPUT_FOLDER);
String jarPath = new URI(SelfExtractorCmd.class.getProtectionDomain()
.getCodeSource().getLocation().getFile()).getPath();
//-- Stopping service
if(System.getProperty("os.name").toLowerCase().indexOf("win") != -1){
System.out.println("");
printInfoLog("Stop wiperdog service: Start");
stopService();
printInfoLog("Stop wiperdog service: End");
}
unZip(jarPath, OUTPUT_FOLDER);
String newJarPath = (System.getProperty("os.name").toLowerCase()
.indexOf("win") != -1) ? jarPath.substring(1, jarPath
.length()) : jarPath;
try {
fo.flush();
fo.close();
} catch (Exception e) {
fo.flush();
fo.close();
e.printStackTrace();
}
/**
Before running Groovy script:
1. Set log file name for groovy because groovy will have user.dir as WIPERDOG_HOME which is different from
SelfExtractor user.dir
2. Setup extractor.xml for installation mode based on -d option (args.length = 0 -> without -d option).
We need to change extractor xm schema to define new INSTALLATION_MODE(see element installMode in extractor.xml)
*/
String logFilePath = LOG_FILE_NAME.replaceAll("\\\\", "/");
try
{
File file = new File(OUTPUT_FOLDER + "/extractor.xml");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\n";
}
reader.close();
String tempText = oldtext.replaceAll("INSTALLER_LOG_PATH", logFilePath);
String newText = tempText.replaceAll("INSTALL_MODE", (strArgs != null && strArgs.indexOf("-ni") != -1)?"interactive":"silient");
FileWriter writer = new FileWriter(OUTPUT_FOLDER + "/extractor.xml");
writer.write(newText);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
// run pre-configuration groovy script
runGroovyInstaller(newJarPath,strArgs);
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Run the installer script written in Groovy
* @param jarPath path to this Jar file, used in classpath for the java process
* @throws Exception any exception
*/
static void runGroovyInstaller(String jarPath,String strArgs)throws Exception{
//- risk when user choose the output directory in another volume, which is different from current volume
String logFilePath = LOG_FILE_NAME.replaceAll("\\\\", "/");
try
{
File file = new File(OUTPUT_FOLDER + "/extractor.xml");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\n";
}
reader.close();
String newtext = oldtext.replaceAll("INSTALLER_LOG_PATH", logFilePath);
FileWriter writer = new FileWriter(OUTPUT_FOLDER + "/extractor.xml");
writer.write(newtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
File workDir = new File(OUTPUT_FOLDER);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
docBuilder.setErrorHandler(new XMLErrorHandler());
Document doc = docBuilder.parse(InstallerUtil.class.getResourceAsStream("/extractor.xml"));
InstallerUtil.parseXml(doc.getDocumentElement());
if(InstallerXML.getInstance().getRunInstallerSyntax() == null || InstallerXML.getInstance().getRunInstallerSyntax().equals(""))
throw new Exception("Cannot run configuration for newly installed Wiperdog");
//Run java process, e.g: java -jar lib/java/bundle/groovy-all-2.2.1.jar installer/installer.groovy
String runInstallerSyntax = InstallerXML.getInstance().getRunInstallerSyntax();
// runInstallerSyntax += " "+OUTPUT_FOLDER + " " + strArgs;
if (runInstallerSyntax != null && !runInstallerSyntax.equals("")) {
String[] cmdArray = runInstallerSyntax.split(" ");
List<String> listCmd = new LinkedList<String>();
if (cmdArray.length > 0) {
if (cmdArray[0].equals("java")) {
cmdArray[0] = System.getProperty("java.home")
+ File.separator + "bin" + File.separator + "java";
}
for(int i=0; i<cmdArray.length;i++){
if(i==2){
String claspathSeparator = (System.getProperty("os.name").toLowerCase().indexOf("win")!=-1)?";":":";
String newCmd = (System.getProperty("os.name").toLowerCase().indexOf("win")==-1)?
(OUTPUT_FOLDER +File.separator+ cmdArray[i] + claspathSeparator + jarPath)
:(cmdArray[i] + claspathSeparator + jarPath);
listCmd.add(newCmd);
} else {
listCmd.add(cmdArray[i]);
}
}
listCmd.add(OUTPUT_FOLDER);
if (strArgs != null && !strArgs.equals("")) {
cmdArray = strArgs.split(" ");
for(int i = 0; i < cmdArray.length; i++){
listCmd.add(cmdArray[i]);
}
}
/*for(String s:listCmd){
System.out.print(s + " ");
}*/
ProcessBuilder builder = new ProcessBuilder(listCmd);
builder.directory(workDir);
builder.redirectErrorStream(true);
Process p = builder.start();
InputStream procOut = p.getInputStream();
OutputStream procIn = p.getOutputStream();
new Thread(new Redirector("Output", procOut, System.out)).start();
new Thread(new Redirector("Input",System.in, procIn)).start();
p.waitFor();
}
}
}
/**
* Extract the jar file
*
* @param zipFile input zip file
* @param outputFolder zip file output folder
*/
public static void unZip(String zipFile, String outputFolder) throws Exception{
byte[] buffer = new byte[1024];
try{
// create output directory is not exists
File folder = new File(outputFolder);
if(!folder.exists()){
folder.mkdir();
}
//------------------------------------
ZipInputStream zis2 = new ZipInputStream(new FileInputStream(zipFile));
// get the zipped file list entry
ZipEntry ze2 = zis2.getNextEntry();
while(ze2!=null ){
String fileName = ze2.getName();
if(!ze2.isDirectory()
&& ! fileName.endsWith(".java")
&& !fileName.endsWith(".class")
&& !fileName.toLowerCase().endsWith(".mf")
&& !fileName.toLowerCase().endsWith("pom.xml")
&& !fileName.toLowerCase().endsWith("pom.properties")
){
File newFile = new File(outputFolder + System.getProperty("file.separator") + fileName);
printInfoLog("Wiperdog installer, unzip to file : "+ newFile.getAbsolutePath());
// create all non exists folders
// else you will hit FileNotFoundException for compressed folder
String parentPath = newFile.getParent();
File parentFolder = new File(parentPath);
if(! parentFolder.exists())
parentFolder.mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis2.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
if (fileName.startsWith("bin")) {
newFile.setExecutable(true);
}
}
ze2 = zis2.getNextEntry();
}
zis2.closeEntry();
zis2.close();
printInfoLog("Self-extracting done!");
}catch(IOException ex){
ex.printStackTrace();
}
}
public static String getParamValue(String[] args, String key){
String ret = null;
for(int i=0;i<args.length;i++){
if(args[i] != null && args[i].equals(key) && ((i+1) < args.length)){
ret = args[i+1];
break;
}
}
return ret;
}
public static boolean containParam(String[] args, String key){
boolean ret = false;
for(String s:args){
if(s != null && s.equals(key)){
ret = true;
break;
}
}
return ret;
}
public static boolean isNumeric(String string){
return string.matches("-?\\d+(\\.\\d+)?");
}
public static void stopService() throws Exception{
File workDir = new File(System.getProperty("user.dir"));
List<String> listCmd = new LinkedList<String>();
listCmd.add("net");
listCmd.add("stop");
listCmd.add("wiperdog");
ProcessBuilder builder = new ProcessBuilder(listCmd);
builder.redirectErrorStream(true);
builder.directory(workDir);
Process p = builder.start();
InputStream procOut = p.getInputStream();
OutputStream procIn = p.getOutputStream();
new Thread(new Redirector(procOut, System.out)).start();
new Thread(new Redirector(System.in, procIn)).start();
p.waitFor();
//-- kill process
listCmd = new LinkedList<String>();
listCmd.add("taskkill");
listCmd.add("/F");
listCmd.add("/IM");
listCmd.add("wiperdog_service*");
builder = new ProcessBuilder(listCmd);
builder.redirectErrorStream(true);
builder.directory(workDir);
p = builder.start();
procOut = p.getInputStream();
procIn = p.getOutputStream();
new Thread(new Redirector(procOut, System.out)).start();
new Thread(new Redirector(System.in, procIn)).start();
p.waitFor();
//-- Wait
listCmd = new LinkedList<String>();
listCmd.add("cmd.exe");
listCmd.add("/c");
listCmd.add("sleep");
listCmd.add("3");
builder = new ProcessBuilder(listCmd);
builder.redirectErrorStream(true);
builder.directory(workDir);
p = builder.start();
procOut = p.getInputStream();
procIn = p.getOutputStream();
new Thread(new Redirector(procOut, System.out)).start();
new Thread(new Redirector(System.in, procIn)).start();
p.waitFor();
}
}
/**
* Standard input/output redirector thread
* @author nguyenvannghia
*
*/
class Redirector implements Runnable {
InputStream in;
OutputStream out;
String name = "";
public Redirector(String name, InputStream in, OutputStream out) {
this.name = name;
this.in = in;
this.out = out;
}
public Redirector(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
public void run() {
synchronized(in){
try {
byte[] buf = new byte[1];
while ( in.read(buf) >= 0) {
out.write(buf);
out.flush();
}
} catch (IOException e) {
//e.printStackTrace();
}
}//- end sync
}
}
| src/main/java/org/wiperdog/installer/SelfExtractorCmd.java | package org.wiperdog.installer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.wiperdog.installer.internal.InstallerUtil;
import org.wiperdog.installer.internal.InstallerXML;
import org.wiperdog.installer.internal.XMLErrorHandler;
import java.text.SimpleDateFormat;
/**
* Self-extractor main class of the installer, it help to peform all major tasks of the installation
* such as: Self-extracting, run groovy for pre-configure.
* @author nguyenvannghia
* Email: [email protected]
*/
public class SelfExtractorCmd {
public static String OUTPUT_FOLDER = "";
public static final String LOG_FILE_NAME = System.getProperty("user.dir")+"/WiperdogInstaller.log";
public static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.S");
public static File loggingFile = new File(LOG_FILE_NAME);
public static FileOutputStream fo = null;
static void printInfoLog(String content) throws Exception{
if(fo == null)
fo = new FileOutputStream(loggingFile, true);
fo.write((content+ "\n").getBytes());
System.out.println(content);
}
public static void fileInfoLog(String content) throws Exception{
if(fo == null)
fo = new FileOutputStream(loggingFile, true);
fo.write((content+ "\n").getBytes());
}
public static void main(String args[]) throws Exception{
try {
// Create a new log file for each time user run the installer
fo = new FileOutputStream(loggingFile);
String beginMessage = "Start the Wiperdog installation at " + df.format(new java.util.Date(System.currentTimeMillis())) + "\n";
fo.write(beginMessage.getBytes());
fo.flush();
fo.close();
fo = null;
} catch (Exception e) {
e.printStackTrace();
}
//Argurments : -d (wiperdog home) ,-j(netty port),-r (restful server port),-m(mongodb host),-p(mongodb port),-n(database name),-u(user database),-pw(password database),-mp(mail policy),-s(install as OS service)
// -jd (job directory ) , -id (instances directory) , -cd (jobclass directory)
List<String> listParams = new ArrayList<String>();
listParams.add("-d");
listParams.add("-j");
listParams.add("-r");
listParams.add("-m");
listParams.add("-jd");
listParams.add("-id");
listParams.add("-td");
listParams.add("-cd");
listParams.add("-p");
listParams.add("-n");
listParams.add("-u");
listParams.add("-pw");
listParams.add("-mp");
listParams.add("-s");
listParams.add("-ni");
List<String> listArgs = Arrays.asList(args);
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader inp = new BufferedReader(converter, 512);
try {
try{
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
public void run(){
try{
printInfoLog("Installer shutdown...");
}catch(Exception exx){
//Ignore exception for shutdown hook.
}
}
}));
}catch(Exception ex){
// In case CTRL + C were pressed
Thread.currentThread().sleep(100);
}
// check command syntax to configure OUTPUT_FOLDER
if (args.length == 0 || containParam(args, "-ni")) {
if(args.length == 0){
printInfoLog("Press any key to start interactive installation or CTRL+C to quit. You can execute default installation with -ni option");
String userConfirmInteractiveMode = inp.readLine().trim();
}
//Get current dir
String currentDir = System.getProperty("user.dir");
//Get jar file name, create install directory name
String jarFileName = new java.io.File(SelfExtractorCmd.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
String wiperdogDirName = "";
if (jarFileName.endsWith(".jar")) {
wiperdogDirName = jarFileName.substring(0, jarFileName.length() - 4);
}
if (wiperdogDirName.endsWith("-unix")) {
wiperdogDirName = wiperdogDirName.substring(0, wiperdogDirName.length() - 5);
}
if (wiperdogDirName.endsWith("-win")) {
wiperdogDirName = wiperdogDirName.substring(0, wiperdogDirName.length() - 4);
}
if (wiperdogDirName == "") {
wiperdogDirName = "wiperdogHome";
}
//wiperdog home path
String wiperdogPath = currentDir + File.separator + wiperdogDirName;
//Check install or not
printInfoLog("You omitted to specify WIPERDOG HOME.");
String confirmStr = "";
if(containParam(args, "-ni")){
if(containParam(args, "-d")){
OUTPUT_FOLDER = getParamValue(args, "-d");
}else
OUTPUT_FOLDER = wiperdogPath;
}else{
while (confirmStr!=null && (!confirmStr.toLowerCase().equalsIgnoreCase("y") && !confirmStr.toLowerCase().equalsIgnoreCase("n"))) {
printInfoLog("Do you want to install wiperdog at " + wiperdogPath + " ? [y/n] :");
confirmStr = inp.readLine().trim();
if (confirmStr.toLowerCase().equalsIgnoreCase("y")) {
OUTPUT_FOLDER = wiperdogPath;
} else if (confirmStr.toLowerCase().equalsIgnoreCase("n")) {
System.exit(0);
}
}
}
} else if ((args.length < 2 && !containParam(args,"-ni")) || (!args[0].trim().equals("-d") && !containParam(args,"-ni")) ) {
printInfoLog("Wrong parameter. Usage:\n \t\t java -jar [Installer Jar] -d [INSTALL_PATH>] \n \t\t or \n \t\t java -jar [Installer Jar] -d [INSTALL_PATH] -j [nettyport] -m [mongodb host] -p [mongodb port] -n [mongodb database name] -u [mongodb user name] -pw [mongodb password] -mp [mail policy] -s [yes/no install as OS service]");
System.exit(0);
}else {
if(containParam(args,"-d"))
OUTPUT_FOLDER = (String) args[1];
}// end if (args.length ==0 || -ni option)
//Prepare arguments for Groovy script running
String strArgs = "";
//Pass all arguments to Groovy class
for(int i = 0; i< args.length; i++ ){
//Get netty port from argurment
if(args[i].equals("-j")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
if( isNumeric(args[i+1])){
strArgs += "-j " + args[i+1] + " ";
i++;
} else {
printInfoLog( "Netty port must be number: " + args[i]);
return;
}
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get restful server port from argurment
if(args[i].equals("-r")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
if( isNumeric(args[i+1])){
strArgs += "-r " + args[i+1] + " ";
i++;
} else {
printInfoLog( "Restful server port must be numeric: " + args[i]);
return;
}
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
// Get job directory from argurment
if (args[i].equals("-jd")) {
if ((args.length > i + 1) && (args[i + 1].trim() != "") && (!listParams.contains(args[i + 1].trim()))) {
strArgs += "-jd " + args[i + 1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
// Get intances directory from argurment
if (args[i].equals("-id")) {
if ((args.length > i + 1) && (args[i + 1].trim() != "") && (!listParams.contains(args[i + 1].trim()))) {
strArgs += "-id " + args[i + 1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
// Get job class directory from argurment
if (args[i].equals("-cd")) {
if ((args.length > i + 1) && (args[i + 1].trim() != "") && (!listParams.contains(args[i + 1].trim()))) {
strArgs += "-cd " + args[i + 1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
// Get trigger directory from argurment
if (args[i].equals("-td")) {
if ((args.length > i + 1) && (args[i + 1].trim() != "") && (!listParams.contains(args[i + 1].trim()))) {
strArgs += "-td " + args[i + 1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get Mongodb Host from argurment
if(args[i].equals("-m")) {
if(( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-m " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get Mongodb Port from argurment
if(args[i].equals("-p")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
if(isNumeric(args[i+1])){
strArgs += "-p " + args[i+1] + " ";
i++;
} else {
printInfoLog("Mongodb port must be number: " + args[i]);
return;
}
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get Mongodb database name from argurment
if(args[i].equals("-n")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-n " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get user connect to database
if(args[i].equals("-u")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-u " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get password connect to database
//String pattern = "[a-zA-Z0-9]+";
if(args[i].equals("-pw")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim())) ){
strArgs += "-pw " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get mail send to policy
if(args[i].equals("-mp")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-mp " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get install wiperdog as service
if(args[i].equals("-s")) {
if( ( args.length > i+1) && (args[i+1].trim() != "") && (!listParams.contains(args[i+1].trim()))){
strArgs += "-s " + args[i+1] + " ";
i++;
} else {
printInfoLog("Incorrect value of params: " + args[i]);
return;
}
}
//Get -ni option
if(args[i].equals("-ni")) {
strArgs += args[i] + " ";
}
}
File outputDir = new File(OUTPUT_FOLDER);
//check if wiperdog home params is not an absolute path
if(!outputDir.isAbsolute()) {
String userDir = System.getProperty("user.dir");
OUTPUT_FOLDER = new File (userDir, OUTPUT_FOLDER).getAbsolutePath();
}
printInfoLog("Wiperdog will be install to directory: "
+ OUTPUT_FOLDER);
String jarPath = new URI(SelfExtractorCmd.class.getProtectionDomain()
.getCodeSource().getLocation().getFile()).getPath();
//-- Stopping service
if(System.getProperty("os.name").toLowerCase().indexOf("win") != -1){
System.out.println("");
printInfoLog("Stop wiperdog service: Start");
stopService();
printInfoLog("Stop wiperdog service: End");
}
unZip(jarPath, OUTPUT_FOLDER);
String newJarPath = (System.getProperty("os.name").toLowerCase()
.indexOf("win") != -1) ? jarPath.substring(1, jarPath
.length()) : jarPath;
try {
fo.flush();
fo.close();
} catch (Exception e) {
fo.flush();
fo.close();
e.printStackTrace();
}
/**
Before running Groovy script:
1. Set log file name for groovy because groovy will have user.dir as WIPERDOG_HOME which is different from
SelfExtractor user.dir
2. Setup extractor.xml for installation mode based on -d option (args.length = 0 -> without -d option).
We need to change extractor xm schema to define new INSTALLATION_MODE(see element installMode in extractor.xml)
*/
String logFilePath = LOG_FILE_NAME.replaceAll("\\\\", "/");
try
{
File file = new File(OUTPUT_FOLDER + "/extractor.xml");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\n";
}
reader.close();
String tempText = oldtext.replaceAll("INSTALLER_LOG_PATH", logFilePath);
String newText = tempText.replaceAll("INSTALL_MODE", (strArgs != null && strArgs.indexOf("-ni") != -1)?"interactive":"silient");
FileWriter writer = new FileWriter(OUTPUT_FOLDER + "/extractor.xml");
writer.write(newText);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
// run pre-configuration groovy script
runGroovyInstaller(newJarPath,strArgs);
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Run the installer script written in Groovy
* @param jarPath path to this Jar file, used in classpath for the java process
* @throws Exception any exception
*/
static void runGroovyInstaller(String jarPath,String strArgs)throws Exception{
//- risk when user choose the output directory in another volume, which is different from current volume
String logFilePath = LOG_FILE_NAME.replaceAll("\\\\", "/");
try
{
File file = new File(OUTPUT_FOLDER + "/extractor.xml");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\n";
}
reader.close();
String newtext = oldtext.replaceAll("INSTALLER_LOG_PATH", logFilePath);
FileWriter writer = new FileWriter(OUTPUT_FOLDER + "/extractor.xml");
writer.write(newtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
File workDir = new File(OUTPUT_FOLDER);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
docBuilder.setErrorHandler(new XMLErrorHandler());
Document doc = docBuilder.parse(InstallerUtil.class.getResourceAsStream("/extractor.xml"));
InstallerUtil.parseXml(doc.getDocumentElement());
if(InstallerXML.getInstance().getRunInstallerSyntax() == null || InstallerXML.getInstance().getRunInstallerSyntax().equals(""))
throw new Exception("Cannot run configuration for newly installed Wiperdog");
//Run java process, e.g: java -jar lib/java/bundle/groovy-all-2.2.1.jar installer/installer.groovy
String runInstallerSyntax = InstallerXML.getInstance().getRunInstallerSyntax();
// runInstallerSyntax += " "+OUTPUT_FOLDER + " " + strArgs;
if (runInstallerSyntax != null && !runInstallerSyntax.equals("")) {
String[] cmdArray = runInstallerSyntax.split(" ");
List<String> listCmd = new LinkedList<String>();
if (cmdArray.length > 0) {
if (cmdArray[0].equals("java")) {
cmdArray[0] = System.getProperty("java.home")
+ File.separator + "bin" + File.separator + "java";
}
for(int i=0; i<cmdArray.length;i++){
if(i==2){
String claspathSeparator = (System.getProperty("os.name").toLowerCase().indexOf("win")!=-1)?";":":";
String newCmd = (System.getProperty("os.name").toLowerCase().indexOf("win")==-1)?
(OUTPUT_FOLDER +File.separator+ cmdArray[i] + claspathSeparator + jarPath)
:(cmdArray[i] + claspathSeparator + jarPath);
listCmd.add(newCmd);
} else {
listCmd.add(cmdArray[i]);
}
}
listCmd.add(OUTPUT_FOLDER);
if (strArgs != null && !strArgs.equals("")) {
cmdArray = strArgs.split(" ");
for(int i = 0; i < cmdArray.length; i++){
listCmd.add(cmdArray[i]);
}
}
/*for(String s:listCmd){
System.out.print(s + " ");
}*/
ProcessBuilder builder = new ProcessBuilder(listCmd);
builder.directory(workDir);
builder.redirectErrorStream(true);
Process p = builder.start();
InputStream procOut = p.getInputStream();
OutputStream procIn = p.getOutputStream();
new Thread(new Redirector("Output", procOut, System.out)).start();
new Thread(new Redirector("Input",System.in, procIn)).start();
p.waitFor();
}
}
}
/**
* Extract the jar file
*
* @param zipFile input zip file
* @param outputFolder zip file output folder
*/
public static void unZip(String zipFile, String outputFolder) throws Exception{
byte[] buffer = new byte[1024];
try{
// create output directory is not exists
File folder = new File(outputFolder);
if(!folder.exists()){
folder.mkdir();
}
//------------------------------------
ZipInputStream zis2 = new ZipInputStream(new FileInputStream(zipFile));
// get the zipped file list entry
ZipEntry ze2 = zis2.getNextEntry();
while(ze2!=null ){
String fileName = ze2.getName();
if(!ze2.isDirectory()
&& ! fileName.endsWith(".java")
&& !fileName.endsWith(".class")
&& !fileName.toLowerCase().endsWith(".mf")
&& !fileName.toLowerCase().endsWith("pom.xml")
&& !fileName.toLowerCase().endsWith("pom.properties")
){
File newFile = new File(outputFolder + System.getProperty("file.separator") + fileName);
printInfoLog("Wiperdog installer, unzip to file : "+ newFile.getAbsolutePath());
// create all non exists folders
// else you will hit FileNotFoundException for compressed folder
String parentPath = newFile.getParent();
File parentFolder = new File(parentPath);
if(! parentFolder.exists())
parentFolder.mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis2.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
if (fileName.startsWith("bin")) {
newFile.setExecutable(true);
}
}
ze2 = zis2.getNextEntry();
}
zis2.closeEntry();
zis2.close();
printInfoLog("Self-extracting done!");
}catch(IOException ex){
ex.printStackTrace();
}
}
public static String getParamValue(String[] args, String key){
String ret = null;
for(int i=0;i<args.length;i++){
if(args[i] != null && args[i].equals(key) && ((i+1) < args.length)){
ret = args[i+1];
break;
}
}
return ret;
}
public static boolean containParam(String[] args, String key){
boolean ret = false;
for(String s:args){
if(s != null && s.equals(key)){
ret = true;
break;
}
}
return ret;
}
public static boolean isNumeric(String string){
return string.matches("-?\\d+(\\.\\d+)?");
}
public static void stopService() throws Exception{
File workDir = new File(System.getProperty("user.dir"));
List<String> listCmd = new LinkedList<String>();
listCmd.add("net");
listCmd.add("stop");
listCmd.add("wiperdog");
ProcessBuilder builder = new ProcessBuilder(listCmd);
builder.redirectErrorStream(true);
builder.directory(workDir);
Process p = builder.start();
InputStream procOut = p.getInputStream();
OutputStream procIn = p.getOutputStream();
new Thread(new Redirector(procOut, System.out)).start();
new Thread(new Redirector(System.in, procIn)).start();
p.waitFor();
//-- kill process
listCmd = new LinkedList<String>();
listCmd.add("taskkill");
listCmd.add("/F");
listCmd.add("/IM");
listCmd.add("wiperdog_service*");
builder = new ProcessBuilder(listCmd);
builder.redirectErrorStream(true);
builder.directory(workDir);
p = builder.start();
procOut = p.getInputStream();
procIn = p.getOutputStream();
new Thread(new Redirector(procOut, System.out)).start();
new Thread(new Redirector(System.in, procIn)).start();
p.waitFor();
//-- Wait
listCmd = new LinkedList<String>();
listCmd.add("cmd.exe");
listCmd.add("/c");
listCmd.add("sleep");
listCmd.add("3");
builder = new ProcessBuilder(listCmd);
builder.redirectErrorStream(true);
builder.directory(workDir);
p = builder.start();
procOut = p.getInputStream();
procIn = p.getOutputStream();
new Thread(new Redirector(procOut, System.out)).start();
new Thread(new Redirector(System.in, procIn)).start();
p.waitFor();
}
}
/**
* Standard input/output redirector thread
* @author nguyenvannghia
*
*/
class Redirector implements Runnable {
InputStream in;
OutputStream out;
String name = "";
public Redirector(String name, InputStream in, OutputStream out) {
this.name = name;
this.in = in;
this.out = out;
}
public Redirector(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
public void run() {
synchronized(in){
try {
byte[] buf = new byte[1];
while ( in.read(buf) >= 0) {
out.write(buf);
out.flush();
}
} catch (IOException e) {
//e.printStackTrace();
}
}//- end sync
}
}
| Update message when installing without parameters + message when incorrect syntax
| src/main/java/org/wiperdog/installer/SelfExtractorCmd.java | Update message when installing without parameters + message when incorrect syntax | <ide><path>rc/main/java/org/wiperdog/installer/SelfExtractorCmd.java
<ide> Thread.currentThread().sleep(100);
<ide> }
<ide> // check command syntax to configure OUTPUT_FOLDER
<add>
<ide> if (args.length == 0 || containParam(args, "-ni")) {
<ide> if(args.length == 0){
<del> printInfoLog("Press any key to start interactive installation or CTRL+C to quit. You can execute default installation with -ni option");
<del> String userConfirmInteractiveMode = inp.readLine().trim();
<add> printInfoLog("Press CTRL+C to quit. You can execute default installation with -ni option");
<ide> }
<ide> //Get current dir
<ide> String currentDir = System.getProperty("user.dir");
<ide> String wiperdogPath = currentDir + File.separator + wiperdogDirName;
<ide>
<ide> //Check install or not
<del> printInfoLog("You omitted to specify WIPERDOG HOME.");
<add>
<ide>
<ide> String confirmStr = "";
<ide> if(containParam(args, "-ni")){
<ide> }
<ide> }
<ide> } else if ((args.length < 2 && !containParam(args,"-ni")) || (!args[0].trim().equals("-d") && !containParam(args,"-ni")) ) {
<del> printInfoLog("Wrong parameter. Usage:\n \t\t java -jar [Installer Jar] -d [INSTALL_PATH>] \n \t\t or \n \t\t java -jar [Installer Jar] -d [INSTALL_PATH] -j [nettyport] -m [mongodb host] -p [mongodb port] -n [mongodb database name] -u [mongodb user name] -pw [mongodb password] -mp [mail policy] -s [yes/no install as OS service]");
<add> printInfoLog("Wrong parameter. Usage:\n \t\t java -jar [Installer Jar] \n \t\t or \n \t\t java -jar [Installer Jar] -d [INSTALL_PATH>] \n \t\t or \n \t\t java -jar [Installer Jar] -d [INSTALL_PATH] -j [nettyport] -m [mongodb host] -p [mongodb port] -n [mongodb database name] -u [mongodb user name] -pw [mongodb password] -mp [mail policy] -s [yes/no install as OS service] \n \t\t or \n \t\t java -jar [Installer Jar] -ni [ -d INSTALL_PATH] [-j nettyport] ... ]");
<ide> System.exit(0);
<ide> }else {
<ide> if(containParam(args,"-d")) |
|
JavaScript | apache-2.0 | 2640a4de6cfc8b78e11f8a882ca1d422bf83c549 | 0 | sitespeedio/browsertime,sitespeedio/browsertime,sitespeedio/browsertime,tobli/browsertime,sitespeedio/browsertime | 'use strict';
const { promisify } = require('util');
const addTextToVideo = require('./addTextToVideo');
const removeOrange = require('./removeOrange');
const path = require('path');
const fs = require('fs');
const get = require('lodash.get');
const rename = promisify(fs.rename);
const unlink = promisify(fs.unlink);
const log = require('intel').getLogger('browsertime.video');
module.exports = async function(
videoDir,
videoPath,
index,
videoMetrics,
timingMetrics,
options
) {
const newStart = videoMetrics.videoRecordingStart / 1000;
let tmpFile = path.join(videoDir, 'tmp.mp4');
// if there's no orange (too slow instance like travis?)
// we don't wanna cut
if (videoMetrics.videoRecordingStart > 0) {
await removeOrange(
videoPath,
tmpFile,
newStart,
videoMetrics.visualMetrics,
options
);
} else {
log.error(
'The video recording start is zero, either no orange is there in the video or VisualMetrics failed: %j',
videoMetrics
);
tmpFile = videoPath;
}
if (get(options, 'videoParams.keepOriginalVideo', false)) {
const originalFile = path.join(videoDir, index + '-original.mp4');
await rename(videoPath, originalFile);
}
if (options.videoParams.addTimer) {
const tmpFile2 = path.join(videoDir, 'tmp2.mp4');
await addTextToVideo(
tmpFile,
tmpFile2,
videoMetrics,
timingMetrics,
options
);
await rename(tmpFile2, videoPath);
await unlink(tmpFile);
} else {
await rename(tmpFile, videoPath);
}
};
| lib/video/postprocessing/finetune/index.js | 'use strict';
const { promisify } = require('util');
const addTextToVideo = require('./addTextToVideo');
const removeOrange = require('./removeOrange');
const path = require('path');
const fs = require('fs');
const get = require('lodash.get');
const rename = promisify(fs.rename);
const unlink = promisify(fs.unlink);
const log = require('intel').getLogger('browsertime.video');
module.exports = async function(
videoDir,
videoPath,
index,
videoMetrics,
timingMetrics,
options
) {
const newStart = videoMetrics.videoRecordingStart / 1000;
let tmpFile = path.join(videoDir, 'tmp.mp4');
// if there's no orange (too slow instance like travis?)
// we don't wanna cut
if (videoMetrics.videoRecordingStart > 0) {
await removeOrange(
videoPath,
tmpFile,
newStart,
videoMetrics.visualMetrics,
options
);
} else {
log.error(
'The video recording start is zero, either no orange is there in the video or VisualMetrics failed.'
);
tmpFile = videoPath;
}
if (get(options, 'videoParams.keepOriginalVideo', false)) {
const originalFile = path.join(videoDir, index + '-original.mp4');
await rename(videoPath, originalFile);
}
if (options.videoParams.addTimer) {
const tmpFile2 = path.join(videoDir, 'tmp2.mp4');
await addTextToVideo(
tmpFile,
tmpFile2,
videoMetrics,
timingMetrics,
options
);
await rename(tmpFile2, videoPath);
await unlink(tmpFile);
} else {
await rename(tmpFile, videoPath);
}
};
| log the video metrics if we get a failure
| lib/video/postprocessing/finetune/index.js | log the video metrics if we get a failure | <ide><path>ib/video/postprocessing/finetune/index.js
<ide> );
<ide> } else {
<ide> log.error(
<del> 'The video recording start is zero, either no orange is there in the video or VisualMetrics failed.'
<add> 'The video recording start is zero, either no orange is there in the video or VisualMetrics failed: %j',
<add> videoMetrics
<ide> );
<ide> tmpFile = videoPath;
<ide> } |
|
Java | apache-2.0 | c6673fa1a6acae081a3bdb782ec1183a2120932c | 0 | ukwa/w3act,ukwa/w3act,ukwa/w3act,ukwa/w3act | package controllers;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import models.CrawlPermission;
import models.DCollection;
import models.Flag;
import models.Organisation;
import models.Tag;
import models.Target;
import models.Taxonomy;
import models.User;
import org.apache.commons.lang3.StringUtils;
import play.Logger;
import play.data.DynamicForm;
import play.data.Form;
import play.data.validation.ValidationError;
import play.libs.Json;
import play.mvc.BodyParser;
import play.mvc.Result;
import play.mvc.Security;
import uk.bl.Const;
import uk.bl.api.Utils;
import uk.bl.exception.WhoisException;
import uk.bl.scope.Scope;
import views.html.licence.ukwalicenceresult;
import views.html.targets.blank;
import views.html.infomessage;
import com.avaje.ebean.Ebean;
import com.fasterxml.jackson.databind.JsonNode;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import views.html.targets.edit;
/**
* Describe W3ACT project.
*/
@Security.Authenticated(Secured.class)
public class TargetController extends AbstractController {
/**
* This method prepares Target form for sending info message
* about errors
* @return edit page with form and info message
*/
public static Result info() {
Target targetObj = new Target();
targetObj.field_url = getFormParam(Const.FIELD_URL_NODE);
targetObj.nid = Long.valueOf(getFormParam(Const.NID));
targetObj.url = Const.ACT_URL + targetObj.nid;
targetObj.author = getFormParam(Const.USER);
targetObj.title = getFormParam(Const.TITLE);
targetObj.field_key_site = Utils.getNormalizeBooleanString(getFormParam(Const.KEYSITE));
targetObj.field_description = getFormParam(Const.DESCRIPTION);
if (getFormParam(Const.FLAG_NOTES) != null) {
targetObj.flag_notes = getFormParam(Const.FLAG_NOTES);
}
if (getFormParam(Const.STATUS) != null) {
targetObj.status = Long.valueOf(getFormParam(Const.STATUS));
}
if (getFormParam(Const.QA_STATUS) != null) {
targetObj.qa_status = getFormParam(Const.QA_STATUS);
}
if (getFormParam(Const.LANGUAGE) != null) {
targetObj.language = getFormParam(Const.LANGUAGE);
}
if (getFormParam(Const.SELECTION_TYPE) != null) {
targetObj.selection_type = getFormParam(Const.SELECTION_TYPE);
}
if (getFormParam(Const.SELECTOR_NOTES) != null) {
targetObj.selector_notes = getFormParam(Const.SELECTOR_NOTES);
}
if (getFormParam(Const.ARCHIVIST_NOTES) != null) {
targetObj.archivist_notes = getFormParam(Const.ARCHIVIST_NOTES);
}
if (getFormParam(Const.LEGACY_SITE_ID) != null
&& getFormParam(Const.LEGACY_SITE_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.LEGACY_SITE_ID))) {
targetObj.legacy_site_id = Long.valueOf(getFormParam(Const.LEGACY_SITE_ID));
}
if (getFormParam(Const.AUTHORS) != null) {
targetObj.authors = getFormParam(Const.AUTHORS);
}
if (getFormParam(Const.LIVE_SITE_STATUS) != null) {
targetObj.field_live_site_status = getFormParam(Const.LIVE_SITE_STATUS);
}
if (getFormParam(Const.FIELD_SUBJECT) != null) {
targetObj.field_subject = Utils.removeDuplicatesFromList(getFormParam(Const.FIELD_SUBJECT));
Logger.debug("targetObj.field_subject: " + targetObj.field_subject);
} else {
targetObj.field_subject = Const.NONE;
}
if (getFormParam(Const.TREE_KEYS) != null) {
targetObj.field_collection_categories = Utils.removeDuplicatesFromList(getFormParam(Const.TREE_KEYS));
}
if (getFormParam(Const.ORGANISATION) != null) {
if (!getFormParam(Const.ORGANISATION).toLowerCase().contains(Const.NONE)) {
targetObj.field_nominating_organisation = Organisation.findByTitle(getFormParam(Const.ORGANISATION)).url;
} else {
targetObj.field_nominating_organisation = Const.NONE;
}
}
if (getFormParam(Const.ORIGINATING_ORGANISATION) != null) {
targetObj.originating_organisation = getFormParam(Const.ORIGINATING_ORGANISATION);
}
if (getFormParam(Const.AUTHOR) != null) {
targetObj.author = User.findByName(getFormParam(Const.AUTHOR)).url;
}
if (getFormParam(Const.TAGS) != null) {
if (!getFormParam(Const.TAGS).toLowerCase().contains(Const.NONE)) {
String[] tags = getFormParams(Const.TAGS);
String resTags = "";
for (String tag: tags)
{
if (tag != null && tag.length() > 0) {
resTags = resTags + Tag.findByName(tag).url + Const.LIST_DELIMITER;
}
}
targetObj.tags = resTags;
} else {
targetObj.tags = Const.NONE;
}
}
if (getFormParam(Const.FLAGS) != null) {
if (!getFormParam(Const.FLAGS).toLowerCase().contains(Const.NONE)) {
String[] flags = getFormParams(Const.FLAGS);
String resFlags = "";
for (String flag: flags)
{
if (flag != null && flag.length() > 0) {
String origFlag = Flags.getNameFromGuiName(flag);
resFlags = resFlags + Flag.findByName(origFlag).url + Const.LIST_DELIMITER;
}
}
targetObj.flags = resFlags;
} else {
targetObj.flags = Const.NONE;
}
}
targetObj.justification = getFormParam(Const.JUSTIFICATION);
targetObj.summary = getFormParam(Const.SUMMARY);
targetObj.revision = getFormParam(Const.REVISION);
if (getFormParam(Const.FIELD_WCT_ID) != null
&& getFormParam(Const.FIELD_WCT_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.FIELD_WCT_ID))) {
targetObj.field_wct_id = Long.valueOf(getFormParam(Const.FIELD_WCT_ID));
}
if (getFormParam(Const.FIELD_SPT_ID) != null
&& getFormParam(Const.FIELD_SPT_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.FIELD_SPT_ID))) {
targetObj.field_spt_id = Long.valueOf(getFormParam(Const.FIELD_SPT_ID));
}
if (getFormParam(Const.FIELD_LICENSE) != null) {
if (!getFormParam(Const.FIELD_LICENSE).toLowerCase().contains(Const.NONE)) {
String[] licenses = getFormParams(Const.FIELD_LICENSE);
String resLicenses = "";
for (String curLicense: licenses)
{
if (curLicense != null && curLicense.length() > 0) {
resLicenses = resLicenses + Taxonomy.findByFullNameExt(curLicense, Const.LICENCE).url + Const.LIST_DELIMITER;
}
}
targetObj.field_license = resLicenses;
} else {
targetObj.field_license = Const.NONE;
}
}
targetObj.field_uk_hosting = Target.checkUkHosting(targetObj.field_url);
targetObj.field_uk_postal_address = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_UK_POSTAL_ADDRESS));
targetObj.field_uk_postal_address_url = getFormParam(Const.FIELD_UK_POSTAL_ADDRESS_URL);
targetObj.field_via_correspondence = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_VIA_CORRESPONDENCE));
targetObj.value = getFormParam(Const.FIELD_NOTES);
targetObj.field_professional_judgement = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_PROFESSIONAL_JUDGEMENT));
targetObj.field_professional_judgement_exp = getFormParam(Const.FIELD_PROFESSIONAL_JUDGEMENT_EXP);
targetObj.field_no_ld_criteria_met = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_NO_LD_CRITERIA_MET));
targetObj.field_ignore_robots_txt = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_IGNORE_ROBOTS_TXT));
if (getFormParam(Const.FIELD_CRAWL_START_DATE) != null) {
String startDateHumanView = getFormParam(Const.FIELD_CRAWL_START_DATE);
String startDateUnix = Utils.getUnixDateStringFromDate(startDateHumanView);
targetObj.field_crawl_start_date = startDateUnix;
}
targetObj.date_of_publication = getFormParam(Const.DATE_OF_PUBLICATION);
targetObj.field_crawl_end_date = getFormParam(Const.FIELD_CRAWL_END_DATE);
if (getFormParam(Const.FIELD_CRAWL_END_DATE) != null) {
String endDateHumanView = getFormParam(Const.FIELD_CRAWL_END_DATE);
String endDateUnix = Utils.getUnixDateStringFromDate(endDateHumanView);
targetObj.field_crawl_end_date = endDateUnix;
}
targetObj.white_list = getFormParam(Const.WHITE_LIST);
targetObj.black_list = getFormParam(Const.BLACK_LIST);
if (getFormParam(Const.FIELD_DEPTH) != null) {
targetObj.field_depth = Targets.getDepthNameFromGuiName(getFormParam(Const.FIELD_DEPTH));
}
targetObj.field_crawl_frequency = getFormParam(Const.FIELD_CRAWL_FREQUENCY);
if (getFormParam(Const.FIELD_SCOPE) != null) {
targetObj.field_scope = Targets.getScopeNameFromGuiName(getFormParam(Const.FIELD_SCOPE));
}
targetObj.keywords = getFormParam(Const.KEYWORDS);
targetObj.synonyms = getFormParam(Const.SYNONYMS);
targetObj.active = true;
Form<Target> targetFormNew = Form.form(Target.class);
targetFormNew = targetFormNew.fill(targetObj);
return ok(
edit.render(targetFormNew, User.findByEmail(request().username()))
);
}
/**
* This method saves changes on given target in a new target object
* completed by revision comment. The "version" field in the Target object
* contains the timestamp of the change and the last version is marked by
* flag "active". Remaining Target objects with the same URL are not active.
* @return
*/
public static Result saveTarget() {
Result res = null;
String save = getFormParam("save");
String delete = getFormParam("delete");
String request = getFormParam(Const.REQUEST);
String archive = getFormParam(Const.ARCHIVE);
Logger.info("save: " + save);
Logger.info("delete: " + delete);
if (save != null) {
Logger.info("input data for the target saving nid: " + getFormParam(Const.NID) +
", url: " + getFormParam(Const.URL) +
", field_subject: " + getFormParam(Const.FIELD_SUBJECT) +
", field_url: " + getFormParam(Const.FIELD_URL_NODE) +
", title: " + getFormParam(Const.TITLE) + ", keysite: " + getFormParam(Const.KEYSITE) +
", description: " + getFormParam(Const.DESCRIPTION) +
", status: " + getFormParam(Const.STATUS) +
", qa status: " + getFormParam(Const.QA_STATUS) +
", subject: " + getFormParams(Const.SUBJECT) +
", organisation: " + getFormParam(Const.ORGANISATION) +
", live site status: " + getFormParam(Const.LIVE_SITE_STATUS));
Logger.info("treeKeys: " + getFormParam(Const.TREE_KEYS));
Form<Target> targetForm = Form.form(Target.class).bindFromRequest();
if(targetForm.hasErrors()) {
String missingFields = "";
for (String key : targetForm.errors().keySet()) {
Logger.debug("key: " + key);
key = Utils.showMissingField(key);
if (missingFields.length() == 0) {
missingFields = key;
} else {
missingFields = missingFields + Const.COMMA + " " + key;
}
}
Logger.info("form errors size: " + targetForm.errors().size() + ", " + missingFields);
flash("message", "Please fill out all the required fields, marked with a red star. There are required fields in more than one tab. " +
"Missing fields are: " + missingFields);
return info();
}
DynamicForm requestData = Form.form().bindFromRequest();
String title = requestData.get(Const.TITLE);
Logger.info("form title: " + title);
Target target = new Target();
Target newTarget = new Target();
boolean isExisting = true;
try {
target = Target.findById(Long.valueOf(getFormParam(Const.NID)));
} catch (Exception e) {
Logger.info("is not existing exception");
isExisting = false;
}
if (getFormParam(Const.FIELD_WCT_ID) != null
&& (getFormParam(Const.FIELD_WCT_ID).equals("")
|| !Utils.isNumeric(getFormParam(Const.FIELD_WCT_ID)))) {
Logger.info("You may only enter a numeric ID in 'WCT ID'.");
flash("message", "You may only enter a numeric ID in 'WCT ID'.");
return info();
}
if (getFormParam(Const.FIELD_SPT_ID) != null && !getFormParam(Const.FIELD_SPT_ID).equals("")
&& !Utils.isNumeric(getFormParam(Const.FIELD_SPT_ID))) {
Logger.info("You may only enter a numeric ID in 'SPT ID'.");
flash("message", "You may only enter a numeric ID in 'SPT ID'.");
return info();
}
if (getFormParam(Const.LEGACY_SITE_ID) != null && !getFormParam(Const.LEGACY_SITE_ID).equals("")
&& !Utils.isNumeric(getFormParam(Const.LEGACY_SITE_ID))) {
Logger.info("You may only enter a numeric ID in 'LEGACY SITE ID'.");
flash("message", "You may only enter a numeric ID in 'LEGACY SITE ID'.");
return info();
}
if (target == null) {
target = new Target();
Logger.info("is not existing");
isExisting = false;
}
newTarget.nid = Target.createId();
newTarget.url = target.url;
newTarget.author = target.author;
if (target.author == null) {
newTarget.author = getFormParam(Const.USER);
}
newTarget.field_nominating_organisation = target.field_nominating_organisation;
newTarget.title = getFormParam(Const.TITLE);
newTarget.field_url = Scope.normalizeUrl(getFormParam(Const.FIELD_URL_NODE));
newTarget.field_key_site = Utils.getNormalizeBooleanString(getFormParam(Const.KEYSITE));
newTarget.field_description = getFormParam(Const.DESCRIPTION);
if (getFormParam(Const.FLAG_NOTES) != null) {
newTarget.flag_notes = getFormParam(Const.FLAG_NOTES);
}
if (getFormParam(Const.STATUS) != null) {
// Logger.info("status: " + getFormParam(Const.STATUS) + ".");
newTarget.status = Long.valueOf(getFormParam(Const.STATUS));
// Logger.info("status: " + newTarget.status + ".");
}
if (getFormParam(Const.QA_STATUS) != null) {
Logger.debug("### QA_STATUS");
newTarget.qa_status = getFormParam(Const.QA_STATUS);
CrawlPermissions.updateAllByTargetStatusChange(newTarget.field_url, newTarget.qa_status);
}
Logger.info("QA status: " + newTarget.qa_status + ", getFormParam(Const.QA_STATUS): " + getFormParam(Const.QA_STATUS));
if (getFormParam(Const.LANGUAGE) != null) {
// Logger.info("language: " + getFormParam(Const.LANGUAGE) + ".");
newTarget.language = getFormParam(Const.LANGUAGE);
}
if (getFormParam(Const.SELECTION_TYPE) != null) {
newTarget.selection_type = getFormParam(Const.SELECTION_TYPE);
}
if (getFormParam(Const.SELECTOR_NOTES) != null) {
newTarget.selector_notes = getFormParam(Const.SELECTOR_NOTES);
}
if (getFormParam(Const.ARCHIVIST_NOTES) != null) {
newTarget.archivist_notes = getFormParam(Const.ARCHIVIST_NOTES);
}
if (getFormParam(Const.LEGACY_SITE_ID) != null
&& getFormParam(Const.LEGACY_SITE_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.LEGACY_SITE_ID))) {
Logger.info("legacy site id: " + getFormParam(Const.LEGACY_SITE_ID) + ".");
newTarget.legacy_site_id = Long.valueOf(getFormParam(Const.LEGACY_SITE_ID));
}
Logger.info("authors: " + getFormParam(Const.AUTHORS) + ".");
if (getFormParam(Const.AUTHORS) != null) {
newTarget.authors = getFormParam(Const.AUTHORS);
}
if (getFormParam(Const.LIVE_SITE_STATUS) != null) {
newTarget.field_live_site_status = getFormParam(Const.LIVE_SITE_STATUS);
}
if (getFormParam(Const.FIELD_SUBJECT) != null) {
newTarget.field_subject = Utils.removeDuplicatesFromList(getFormParam(Const.FIELD_SUBJECT));
Logger.debug("newTarget.field_subject: " + newTarget.field_subject);
} else {
newTarget.field_subject = Const.NONE;
}
if (getFormParam(Const.TREE_KEYS) != null) {
newTarget.field_collection_categories = Utils.removeDuplicatesFromList(getFormParam(Const.TREE_KEYS));
Logger.debug("newTarget.field_collection_categories: " + newTarget.field_collection_categories);
}
if (getFormParam(Const.ORGANISATION) != null) {
if (!getFormParam(Const.ORGANISATION).toLowerCase().contains(Const.NONE)) {
Logger.info("nominating organisation: " + getFormParam(Const.ORGANISATION));
newTarget.field_nominating_organisation = Organisation.findByTitle(getFormParam(Const.ORGANISATION)).url;
} else {
newTarget.field_nominating_organisation = Const.NONE;
}
}
if (getFormParam(Const.ORIGINATING_ORGANISATION) != null) {
newTarget.originating_organisation = getFormParam(Const.ORIGINATING_ORGANISATION);
}
// Logger.info("author: " + getFormParam(Const.AUTHOR) + ", user: " + User.findByName(getFormParam(Const.AUTHOR)).url);
if (getFormParam(Const.AUTHOR) != null) {
newTarget.author = User.findByName(getFormParam(Const.AUTHOR)).url;
}
if (getFormParam(Const.TAGS) != null) {
if (!getFormParam(Const.TAGS).toLowerCase().contains(Const.NONE)) {
String[] tags = getFormParams(Const.TAGS);
String resTags = "";
for (String tag: tags)
{
if (tag != null && tag.length() > 0) {
Logger.info("add tag: " + tag);
resTags = resTags + Tag.findByName(tag).url + Const.LIST_DELIMITER;
}
}
newTarget.tags = resTags;
} else {
newTarget.tags = Const.NONE;
}
}
if (getFormParam(Const.FLAGS) != null) {
if (!getFormParam(Const.FLAGS).toLowerCase().contains(Const.NONE)) {
String[] flags = getFormParams(Const.FLAGS);
String resFlags = "";
for (String flag: flags)
{
if (flag != null && flag.length() > 0) {
Logger.info("add flag: " + flag);
String origFlag = Flags.getNameFromGuiName(flag);
Logger.info("original flag name: " + origFlag);
resFlags = resFlags + Flag.findByName(origFlag).url + Const.LIST_DELIMITER;
}
}
newTarget.flags = resFlags;
} else {
newTarget.flags = Const.NONE;
}
}
newTarget.justification = getFormParam(Const.JUSTIFICATION);
newTarget.summary = getFormParam(Const.SUMMARY);
newTarget.revision = getFormParam(Const.REVISION);
if (getFormParam(Const.FIELD_WCT_ID) != null
&& getFormParam(Const.FIELD_WCT_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.FIELD_WCT_ID))) {
newTarget.field_wct_id = Long.valueOf(getFormParam(Const.FIELD_WCT_ID));
}
if (getFormParam(Const.FIELD_SPT_ID) != null
&& getFormParam(Const.FIELD_SPT_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.FIELD_SPT_ID))) {
newTarget.field_spt_id = Long.valueOf(getFormParam(Const.FIELD_SPT_ID));
}
if (getFormParam(Const.FIELD_LICENSE) != null) {
if (!getFormParam(Const.FIELD_LICENSE).toLowerCase().contains(Const.NONE)) {
String[] licenses = getFormParams(Const.FIELD_LICENSE);
String resLicenses = "";
for (String curLicense: licenses)
{
if (curLicense != null && curLicense.length() > 0) {
Logger.info("add curLicense: " + curLicense);
if (curLicense.equals(Const.OPEN_UKWA_LICENSE)
&& getFormParam(Const.QA_STATUS) != null
&& !getFormParam(Const.QA_STATUS).equals(Const.CrawlPermissionStatus.GRANTED.name())) {
Logger.info("Saving is not allowed if License='Open UKWA License (2014-)' and Open UKWA License Requests status is anything other than 'Granted'.");
flash("message", "Saving is not allowed if License='Open UKWA License (2014-)' and Open UKWA License Requests status is anything other than 'Granted'.");
return info();
}
resLicenses = resLicenses + Taxonomy.findByFullNameExt(curLicense, Const.LICENCE).url + Const.LIST_DELIMITER;
}
}
newTarget.field_license = resLicenses;
} else {
newTarget.field_license = Const.NONE;
}
}
newTarget.field_uk_hosting = Target.checkUkHosting(newTarget.field_url);
Logger.debug("field_uk_hosting: " + newTarget.field_uk_hosting);
newTarget.field_uk_postal_address = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_UK_POSTAL_ADDRESS));
newTarget.field_uk_postal_address_url = getFormParam(Const.FIELD_UK_POSTAL_ADDRESS_URL);
Logger.debug("newTarget.field_uk_postal_address: " + newTarget.field_uk_postal_address);
if (newTarget.field_uk_postal_address
&& (newTarget.field_uk_postal_address_url == null || newTarget.field_uk_postal_address_url.length() == 0)) {
Logger.info("If UK Postal Address field has value 'Yes', the Postal Address URL is required.");
flash("message", "If UK Postal Address field has value 'Yes', the Postal Address URL is required.");
return info();
}
newTarget.field_via_correspondence = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_VIA_CORRESPONDENCE));
newTarget.value = getFormParam(Const.FIELD_NOTES);
if (newTarget.field_via_correspondence
&& (newTarget.value == null || newTarget.value.length() == 0)) {
Logger.info("If Via Correspondence field has value 'Yes', the Notes field is required.");
flash("message", "If Via Correspondence field has value 'Yes', the Notes field is required.");
return info();
}
newTarget.field_professional_judgement = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_PROFESSIONAL_JUDGEMENT));
newTarget.field_professional_judgement_exp = getFormParam(Const.FIELD_PROFESSIONAL_JUDGEMENT_EXP);
Logger.debug("newTarget.field_professional_judgement: " + newTarget.field_professional_judgement);
if (newTarget.field_professional_judgement
&& (newTarget.field_professional_judgement_exp == null || newTarget.field_professional_judgement_exp.length() == 0)) {
Logger.info("If Professional Judgement field has value 'Yes', the Professional Judgment Explanation field is required.");
flash("message", "If Professional Judgement field has value 'Yes', the Professional Judgment Explanation field is required.");
return info();
}
newTarget.field_no_ld_criteria_met = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_NO_LD_CRITERIA_MET));
// Logger.info("ignore robots: " + getFormParam(Const.FIELD_IGNORE_ROBOTS_TXT));
newTarget.field_ignore_robots_txt = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_IGNORE_ROBOTS_TXT));
if (getFormParam(Const.FIELD_CRAWL_START_DATE) != null) {
String startDateHumanView = getFormParam(Const.FIELD_CRAWL_START_DATE);
String startDateUnix = Utils.getUnixDateStringFromDate(startDateHumanView);
Logger.info("startDateHumanView: " + startDateHumanView + ", startDateUnix: " + startDateUnix);
newTarget.field_crawl_start_date = startDateUnix;
}
newTarget.date_of_publication = getFormParam(Const.DATE_OF_PUBLICATION);
newTarget.field_crawl_end_date = getFormParam(Const.FIELD_CRAWL_END_DATE);
if (getFormParam(Const.FIELD_CRAWL_END_DATE) != null) {
String endDateHumanView = getFormParam(Const.FIELD_CRAWL_END_DATE);
String endDateUnix = Utils.getUnixDateStringFromDate(endDateHumanView);
Logger.info("endDateHumanView: " + endDateHumanView + ", endDateUnix: " + endDateUnix);
newTarget.field_crawl_end_date = endDateUnix;
}
newTarget.white_list = getFormParam(Const.WHITE_LIST);
newTarget.black_list = getFormParam(Const.BLACK_LIST);
if (getFormParam(Const.FIELD_DEPTH) != null) {
newTarget.field_depth = Targets.getDepthNameFromGuiName(getFormParam(Const.FIELD_DEPTH));
}
newTarget.field_crawl_frequency = getFormParam(Const.FIELD_CRAWL_FREQUENCY);
if (getFormParam(Const.FIELD_SCOPE) != null) {
newTarget.field_scope = Targets.getScopeNameFromGuiName(getFormParam(Const.FIELD_SCOPE));
}
newTarget.keywords = getFormParam(Const.KEYWORDS);
newTarget.synonyms = getFormParam(Const.SYNONYMS);
newTarget.active = true;
long unixTime = System.currentTimeMillis() / 1000L;
String changedTime = String.valueOf(unixTime);
Logger.info("changed time: " + changedTime);
if (!isExisting) {
newTarget.url = Const.ACT_URL + newTarget.nid;
newTarget.edit_url = Const.WCT_URL + newTarget.nid;
} else {
target.active = false;
if (target.field_url != null) {
Logger.info("current target field_url: " + target.field_url);
target.domain = Scope.getDomainFromUrl(target.field_url);
}
target.changed = changedTime;
Logger.info("update target: " + target.nid + ", obj: " + target.toString());
boolean newScope = Target.isInScopeIp(target.field_url, target.url);
Scope.updateLookupEntry(target, newScope);
Ebean.update(target);
}
if (newTarget.field_url != null) {
Logger.info("current target field_url: " + newTarget.field_url);
newTarget.domain = Scope.getDomainFromUrl(newTarget.field_url);
}
newTarget.changed = changedTime;
if (newTarget.created == null || newTarget.created.length() == 0) {
newTarget.created = changedTime;
}
boolean newScope = Target.isInScopeIp(newTarget.field_url, newTarget.url);
Scope.updateLookupEntry(newTarget, newScope);
Ebean.save(newTarget);
Logger.info("save target: " + newTarget.toString());
res = redirect(routes.Targets.edit(newTarget.url));
} // end of save
if (delete != null) {
Long id = Long.valueOf(getFormParam(Const.NID));
Logger.info("deleting: " + id);
Target target = Target.findById(id);
Ebean.delete(target);
res = redirect(routes.Targets.index());
}
if (request != null) {
Logger.debug("request permission for title: " + getFormParam(Const.TITLE) +
" and target: " + getFormParam(Const.FIELD_URL_NODE));
if (getFormParam(Const.TITLE) != null && getFormParam(Const.FIELD_URL_NODE) != null) {
String name = getFormParam(Const.TITLE);
String target = Scope.normalizeUrl(getFormParam(Const.FIELD_URL_NODE));
res = redirect(routes.CrawlPermissions.licenceRequestForTarget(name, target));
}
}
if (archive != null) {
Logger.debug("archive target title: " + getFormParam(Const.TITLE) +
" with URL: " + getFormParam(Const.FIELD_URL_NODE));
if (getFormParam(Const.FIELD_URL_NODE) != null) {
String target = Scope.normalizeUrl(getFormParam(Const.FIELD_URL_NODE));
res = redirect(routes.TargetController.archiveTarget(target));
}
}
return res;
}
/**
* This method pushes a message onto a RabbitMQ queue for given target
* using global settings from project configuration file.
* @param target The field URL of the target
* @return
*/
public static Result archiveTarget(String target) {
Logger.debug("archiveTarget() " + target);
if (target != null && target.length() > 0) {
Properties props = System.getProperties();
Properties customProps = new Properties();
String queueHost = "";
String queuePort = "";
String queueName = "";
String routingKey= "";
String exchangeName = "";
try {
customProps.load(new FileInputStream(Const.PROJECT_PROPERTY_FILE));
for(String key : customProps.stringPropertyNames()) {
String value = customProps.getProperty(key);
// Logger.debug("archiveTarget() key: " + key + " => " + value);
if (key.equals(Const.QUEUE_HOST)) {
queueHost = value;
Logger.debug("archiveTarget() queue host: " + value);
}
if (key.equals(Const.QUEUE_PORT)) {
queuePort = value;
Logger.debug("archiveTarget() queue port: " + value);
}
if (key.equals(Const.QUEUE_NAME)) {
queueName = value;
Logger.debug("archiveTarget() queue name: " + value);
}
if (key.equals(Const.ROUTING_KEY)) {
routingKey = value;
Logger.debug("archiveTarget() routing key: " + value);
}
if (key.equals(Const.EXCHANGE_NAME)) {
exchangeName = value;
Logger.debug("archiveTarget() exchange name: " + value);
}
}
ConnectionFactory factory = new ConnectionFactory();
if (queueHost != null) {
factory.setHost(queueHost);
}
if (queuePort != null) {
factory.setPort(Integer.parseInt(queuePort));
}
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchangeName, "direct", true);
channel.queueDeclare(queueName, true, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey);
String message = target;
channel.basicPublish(exchangeName, routingKey, null, message.getBytes());
Logger.debug(" ### sent target '" + message + "' to queue");
channel.close();
connection.close();
} catch (IOException e) {
Logger.error("Target archiving error: " + e.getMessage());
return ok(infomessage.render("Target archiving error: " + e.getMessage()));
}
} else {
Logger.debug("Target field for archiving is empty");
return ok(infomessage.render("Target archiving error. Target field for archiving is empty"));
}
return ok(
ukwalicenceresult.render()
);
}
/**
* This method is checking scope for given URL and returns result in JSON format.
* @param url
* @return JSON result
* @throws WhoisException
*/
public static Result isInScope(String url) throws WhoisException {
// Logger.info("isInScope controller: " + url);
boolean res = Target.isInScope(url, null);
// Logger.info("isInScope res: " + res);
return ok(Json.toJson(res));
}
/**
* This method calculates collection children - objects that have parents.
* @param url The identifier for parent
* @param targetUrl This is an identifier for current target object
* @return child collection in JSON form
*/
public static String getChildren(String url, String targetUrl) {
// Logger.info("getChildren() target URL: " + targetUrl);
String res = "";
final StringBuffer sb = new StringBuffer();
sb.append(", \"children\":");
List<DCollection> childSuggestedCollections = DCollection.getChildLevelCollections(url);
if (childSuggestedCollections.size() > 0) {
sb.append(getTreeElements(childSuggestedCollections, targetUrl, false));
res = sb.toString();
// Logger.info("getChildren() res: " + res);
}
return res;
}
/**
* Mark collections that are stored in target object as selected
* @param collectionUrl The collection identifier
* @param targetUrl This is an identifier for current target object
* @return
*/
public static String checkSelection(String collectionUrl, String targetUrl) {
String res = "";
if (targetUrl != null && targetUrl.length() > 0) {
Target target = Target.findByUrl(targetUrl);
if (target.field_collection_categories != null &&
target.field_collection_categories.contains(collectionUrl)) {
res = "\"select\": true ,";
}
}
return res;
}
/**
* This method calculates first order collections.
* @param collectionList The list of all collections
* @param targetUrl This is an identifier for current target object
* @param parent This parameter is used to differentiate between root and children nodes
* @return collection object in JSON form
*/
public static String getTreeElements(List<DCollection> collectionList, String targetUrl, boolean parent) {
// Logger.info("getTreeElements() target URL: " + targetUrl);
String res = "";
if (collectionList.size() > 0) {
final StringBuffer sb = new StringBuffer();
sb.append("[");
Iterator<DCollection> itr = collectionList.iterator();
boolean firstTime = true;
while (itr.hasNext()) {
DCollection collection = itr.next();
// Logger.debug("add collection: " + collection.title + ", with url: " + collection.url +
// ", parent:" + collection.parent + ", parent size: " + collection.parent.length());
if ((parent && collection.parent.length() == 0) || !parent || collection.parent.equals(Const.NONE_VALUE)) {
if (firstTime) {
firstTime = false;
} else {
sb.append(", ");
}
// Logger.debug("added");
sb.append("{\"title\": \"" + collection.title + "\"," + checkSelection(collection.url, targetUrl) +
" \"key\": \"" + collection.url + "\"" +
getChildren(collection.url, targetUrl) + "}");
}
}
// Logger.info("collectionList level size: " + collectionList.size());
sb.append("]");
res = sb.toString();
// Logger.info("getTreeElements() res: " + res);
}
return res;
}
/**
* This method computes a tree of collections in JSON format.
* @param targetUrl This is an identifier for current target object
* @return tree structure
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result getSuggestedCollections(String targetUrl) {
Logger.info("getSuggestedCollections() target URL: " + targetUrl);
JsonNode jsonData = null;
final StringBuffer sb = new StringBuffer();
List<DCollection> suggestedCollections = DCollection.getFirstLevelCollections();
sb.append(getTreeElements(suggestedCollections, targetUrl, true));
Logger.info("collections main level size: " + suggestedCollections.size());
jsonData = Json.toJson(Json.parse(sb.toString()));
Logger.info("getCollections() json: " + jsonData.toString());
return ok(jsonData);
}
/**
* This method calculates subject children - objects that have parents.
* @param url The identifier for parent
* @param targetUrl This is an identifier for current target object
* @return child subject in JSON form
*/
public static String getSubjectChildren(String url, String targetUrl) {
// Logger.info("getSubjectChildren() target URL: " + targetUrl);
String res = "";
final StringBuffer sb = new StringBuffer();
sb.append(", \"children\":");
// List<Taxonomy> childSubject = Taxonomy.findListByType(Const.SUBSUBJECT);
Taxonomy subject = Taxonomy.findByUrl(url);
List<Taxonomy> childSubject = Taxonomy.findSubSubjectsList(subject.name);
if (childSubject.size() > 0) {
sb.append(getSubjectTreeElements(childSubject, targetUrl, false));
res = sb.toString();
// Logger.info("getSubjectChildren() res: " + res);
}
return res;
}
/**
* Mark subjects that are stored in target object as selected
* @param subjectUrl The subject identifier
* @param targetUrl This is an identifier for current target object
* @return
*/
public static String checkSubjectSelection(String subjectUrl, String targetUrl) {
String res = "";
if (targetUrl != null && targetUrl.length() > 0) {
Target target = Target.findByUrl(targetUrl);
if (target.field_subject != null &&
target.field_subject.contains(subjectUrl)) {
res = "\"select\": true ,";
}
}
return res;
}
/**
* Check if none value is selected
* @param subjectUrl The subject identifier
* @param targetUrl This is an identifier for current target object
* @return
*/
public static String checkNone(String targetUrl) {
String res = "";
if (targetUrl != null && targetUrl.length() > 0) {
Target target = Target.findByUrl(targetUrl);
if (target.field_subject != null
&& (target.field_subject.toLowerCase().contains(Const.NONE.toLowerCase()))) {
res = "\"select\": true ,";
}
}
return res;
}
/**
* This method calculates first order subjects.
* @param subjectList The list of all subjects
* @param targetUrl This is an identifier for current target object
* @param parent This parameter is used to differentiate between root and children nodes
* @return collection object in JSON form
*/
public static String getSubjectTreeElements(List<Taxonomy> subjectList, String targetUrl, boolean parent) {
// Logger.info("getSubjectTreeElements() target URL: " + targetUrl);
String res = "";
if (subjectList.size() > 0) {
final StringBuffer sb = new StringBuffer();
sb.append("[");
if (parent) {
sb.append("{\"title\": \"" + "None" + "\"," + checkNone(targetUrl) +
" \"key\": \"" + "None" + "\"" + "}, ");
}
Iterator<Taxonomy> itr = subjectList.iterator();
boolean firstTime = true;
while (itr.hasNext()) {
Taxonomy subject = itr.next();
// Logger.debug("add subject: " + subject.name + ", with url: " + subject.url +
// ", parent:" + subject.parent + ", parent size: " + subject.parent.length());
if ((parent && subject.parent.length() == 0) || !parent) {
if (firstTime) {
firstTime = false;
} else {
sb.append(", ");
}
// Logger.debug("added");
sb.append("{\"title\": \"" + subject.name + "\"," + checkSubjectSelection(subject.url, targetUrl) +
" \"key\": \"" + subject.url + "\"" +
getSubjectChildren(subject.url, targetUrl) + "}");
}
}
// Logger.info("subjectList level size: " + subjectList.size());
sb.append("]");
res = sb.toString();
// Logger.info("getSubjectTreeElements() res: " + res);
}
return res;
}
/**
* This method computes a tree of subjects in JSON format.
* @param targetUrl This is an identifier for current target object
* @return tree structure
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result getSubjectTree(String targetUrl) {
Logger.info("getSubjectTree() target URL: " + targetUrl);
JsonNode jsonData = null;
final StringBuffer sb = new StringBuffer();
List<Taxonomy> parentSubjects = Taxonomy.findListByTypeSorted(Const.SUBJECT);
// Logger.info("getSubjectTree() parentSubjects: " + parentSubjects.size());
sb.append(getSubjectTreeElements(parentSubjects, targetUrl, true));
// Logger.info("subjects main level size: " + parentSubjects.size());
jsonData = Json.toJson(Json.parse(sb.toString()));
// Logger.info("getSubjectTree() json: " + jsonData.toString());
return ok(jsonData);
}
}
| app/controllers/TargetController.java | package controllers;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import models.CrawlPermission;
import models.DCollection;
import models.Flag;
import models.Organisation;
import models.Tag;
import models.Target;
import models.Taxonomy;
import models.User;
import org.apache.commons.lang3.StringUtils;
import play.Logger;
import play.data.DynamicForm;
import play.data.Form;
import play.data.validation.ValidationError;
import play.libs.Json;
import play.mvc.BodyParser;
import play.mvc.Result;
import play.mvc.Security;
import uk.bl.Const;
import uk.bl.api.Utils;
import uk.bl.exception.WhoisException;
import uk.bl.scope.Scope;
import views.html.licence.ukwalicenceresult;
import views.html.targets.blank;
import views.html.infomessage;
import com.avaje.ebean.Ebean;
import com.fasterxml.jackson.databind.JsonNode;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import views.html.targets.edit;
/**
* Describe W3ACT project.
*/
@Security.Authenticated(Secured.class)
public class TargetController extends AbstractController {
/**
* This method prepares Target form for sending info message
* about errors
* @return edit page with form and info message
*/
public static Result info() {
Target targetObj = new Target();
targetObj.field_url = getFormParam(Const.FIELD_URL_NODE);
targetObj.nid = Long.valueOf(getFormParam(Const.NID));
targetObj.url = Const.ACT_URL + targetObj.nid;
targetObj.author = getFormParam(Const.USER);
targetObj.title = getFormParam(Const.TITLE);
targetObj.field_key_site = Utils.getNormalizeBooleanString(getFormParam(Const.KEYSITE));
targetObj.field_description = getFormParam(Const.DESCRIPTION);
if (getFormParam(Const.FLAG_NOTES) != null) {
targetObj.flag_notes = getFormParam(Const.FLAG_NOTES);
}
if (getFormParam(Const.STATUS) != null) {
targetObj.status = Long.valueOf(getFormParam(Const.STATUS));
}
if (getFormParam(Const.QA_STATUS) != null) {
targetObj.qa_status = getFormParam(Const.QA_STATUS);
}
if (getFormParam(Const.LANGUAGE) != null) {
targetObj.language = getFormParam(Const.LANGUAGE);
}
if (getFormParam(Const.SELECTION_TYPE) != null) {
targetObj.selection_type = getFormParam(Const.SELECTION_TYPE);
}
if (getFormParam(Const.SELECTOR_NOTES) != null) {
targetObj.selector_notes = getFormParam(Const.SELECTOR_NOTES);
}
if (getFormParam(Const.ARCHIVIST_NOTES) != null) {
targetObj.archivist_notes = getFormParam(Const.ARCHIVIST_NOTES);
}
if (getFormParam(Const.LEGACY_SITE_ID) != null
&& getFormParam(Const.LEGACY_SITE_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.LEGACY_SITE_ID))) {
targetObj.legacy_site_id = Long.valueOf(getFormParam(Const.LEGACY_SITE_ID));
}
if (getFormParam(Const.AUTHORS) != null) {
targetObj.authors = getFormParam(Const.AUTHORS);
}
if (getFormParam(Const.LIVE_SITE_STATUS) != null) {
targetObj.field_live_site_status = getFormParam(Const.LIVE_SITE_STATUS);
}
if (getFormParam(Const.FIELD_SUBJECT) != null) {
targetObj.field_subject = Utils.removeDuplicatesFromList(getFormParam(Const.FIELD_SUBJECT));
Logger.debug("targetObj.field_subject: " + targetObj.field_subject);
} else {
targetObj.field_subject = Const.NONE;
}
if (getFormParam(Const.TREE_KEYS) != null) {
targetObj.field_collection_categories = Utils.removeDuplicatesFromList(getFormParam(Const.TREE_KEYS));
}
if (getFormParam(Const.ORGANISATION) != null) {
if (!getFormParam(Const.ORGANISATION).toLowerCase().contains(Const.NONE)) {
targetObj.field_nominating_organisation = Organisation.findByTitle(getFormParam(Const.ORGANISATION)).url;
} else {
targetObj.field_nominating_organisation = Const.NONE;
}
}
if (getFormParam(Const.ORIGINATING_ORGANISATION) != null) {
targetObj.originating_organisation = getFormParam(Const.ORIGINATING_ORGANISATION);
}
if (getFormParam(Const.AUTHOR) != null) {
targetObj.author = User.findByName(getFormParam(Const.AUTHOR)).url;
}
if (getFormParam(Const.TAGS) != null) {
if (!getFormParam(Const.TAGS).toLowerCase().contains(Const.NONE)) {
String[] tags = getFormParams(Const.TAGS);
String resTags = "";
for (String tag: tags)
{
if (tag != null && tag.length() > 0) {
resTags = resTags + Tag.findByName(tag).url + Const.LIST_DELIMITER;
}
}
targetObj.tags = resTags;
} else {
targetObj.tags = Const.NONE;
}
}
if (getFormParam(Const.FLAGS) != null) {
if (!getFormParam(Const.FLAGS).toLowerCase().contains(Const.NONE)) {
String[] flags = getFormParams(Const.FLAGS);
String resFlags = "";
for (String flag: flags)
{
if (flag != null && flag.length() > 0) {
String origFlag = Flags.getNameFromGuiName(flag);
resFlags = resFlags + Flag.findByName(origFlag).url + Const.LIST_DELIMITER;
}
}
targetObj.flags = resFlags;
} else {
targetObj.flags = Const.NONE;
}
}
targetObj.justification = getFormParam(Const.JUSTIFICATION);
targetObj.summary = getFormParam(Const.SUMMARY);
targetObj.revision = getFormParam(Const.REVISION);
if (getFormParam(Const.FIELD_WCT_ID) != null
&& getFormParam(Const.FIELD_WCT_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.FIELD_WCT_ID))) {
targetObj.field_wct_id = Long.valueOf(getFormParam(Const.FIELD_WCT_ID));
}
if (getFormParam(Const.FIELD_SPT_ID) != null
&& getFormParam(Const.FIELD_SPT_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.FIELD_SPT_ID))) {
targetObj.field_spt_id = Long.valueOf(getFormParam(Const.FIELD_SPT_ID));
}
if (getFormParam(Const.FIELD_LICENSE) != null) {
if (!getFormParam(Const.FIELD_LICENSE).toLowerCase().contains(Const.NONE)) {
String[] licenses = getFormParams(Const.FIELD_LICENSE);
String resLicenses = "";
for (String curLicense: licenses)
{
if (curLicense != null && curLicense.length() > 0) {
resLicenses = resLicenses + Taxonomy.findByFullNameExt(curLicense, Const.LICENCE).url + Const.LIST_DELIMITER;
}
}
targetObj.field_license = resLicenses;
} else {
targetObj.field_license = Const.NONE;
}
}
targetObj.field_uk_hosting = Target.checkUkHosting(targetObj.field_url);
targetObj.field_uk_postal_address = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_UK_POSTAL_ADDRESS));
targetObj.field_uk_postal_address_url = getFormParam(Const.FIELD_UK_POSTAL_ADDRESS_URL);
targetObj.field_via_correspondence = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_VIA_CORRESPONDENCE));
targetObj.value = getFormParam(Const.FIELD_NOTES);
targetObj.field_professional_judgement = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_PROFESSIONAL_JUDGEMENT));
targetObj.field_professional_judgement_exp = getFormParam(Const.FIELD_PROFESSIONAL_JUDGEMENT_EXP);
targetObj.field_no_ld_criteria_met = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_NO_LD_CRITERIA_MET));
targetObj.field_ignore_robots_txt = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_IGNORE_ROBOTS_TXT));
if (getFormParam(Const.FIELD_CRAWL_START_DATE) != null) {
String startDateHumanView = getFormParam(Const.FIELD_CRAWL_START_DATE);
String startDateUnix = Utils.getUnixDateStringFromDate(startDateHumanView);
targetObj.field_crawl_start_date = startDateUnix;
}
targetObj.date_of_publication = getFormParam(Const.DATE_OF_PUBLICATION);
targetObj.field_crawl_end_date = getFormParam(Const.FIELD_CRAWL_END_DATE);
if (getFormParam(Const.FIELD_CRAWL_END_DATE) != null) {
String endDateHumanView = getFormParam(Const.FIELD_CRAWL_END_DATE);
String endDateUnix = Utils.getUnixDateStringFromDate(endDateHumanView);
targetObj.field_crawl_end_date = endDateUnix;
}
targetObj.white_list = getFormParam(Const.WHITE_LIST);
targetObj.black_list = getFormParam(Const.BLACK_LIST);
if (getFormParam(Const.FIELD_DEPTH) != null) {
targetObj.field_depth = Targets.getDepthNameFromGuiName(getFormParam(Const.FIELD_DEPTH));
}
targetObj.field_crawl_frequency = getFormParam(Const.FIELD_CRAWL_FREQUENCY);
if (getFormParam(Const.FIELD_SCOPE) != null) {
targetObj.field_scope = Targets.getScopeNameFromGuiName(getFormParam(Const.FIELD_SCOPE));
}
targetObj.keywords = getFormParam(Const.KEYWORDS);
targetObj.synonyms = getFormParam(Const.SYNONYMS);
targetObj.active = true;
Form<Target> targetFormNew = Form.form(Target.class);
targetFormNew = targetFormNew.fill(targetObj);
return ok(
edit.render(targetFormNew, User.findByEmail(request().username()))
);
}
/**
* This method saves changes on given target in a new target object
* completed by revision comment. The "version" field in the Target object
* contains the timestamp of the change and the last version is marked by
* flag "active". Remaining Target objects with the same URL are not active.
* @return
*/
public static Result saveTarget() {
Result res = null;
String save = getFormParam("save");
String delete = getFormParam("delete");
String request = getFormParam(Const.REQUEST);
String archive = getFormParam(Const.ARCHIVE);
Logger.info("save: " + save);
Logger.info("delete: " + delete);
if (save != null) {
Logger.info("input data for the target saving nid: " + getFormParam(Const.NID) +
", url: " + getFormParam(Const.URL) +
", field_subject: " + getFormParam(Const.FIELD_SUBJECT) +
", field_url: " + getFormParam(Const.FIELD_URL_NODE) +
", title: " + getFormParam(Const.TITLE) + ", keysite: " + getFormParam(Const.KEYSITE) +
", description: " + getFormParam(Const.DESCRIPTION) +
", status: " + getFormParam(Const.STATUS) +
", qa status: " + getFormParam(Const.QA_STATUS) +
", subject: " + getFormParams(Const.SUBJECT) +
", organisation: " + getFormParam(Const.ORGANISATION) +
", live site status: " + getFormParam(Const.LIVE_SITE_STATUS));
Logger.info("treeKeys: " + getFormParam(Const.TREE_KEYS));
Form<Target> targetForm = Form.form(Target.class).bindFromRequest();
if(targetForm.hasErrors()) {
String missingFields = "";
for (String key : targetForm.errors().keySet()) {
Logger.debug("key: " + key);
key = Utils.showMissingField(key);
if (missingFields.length() == 0) {
missingFields = key;
} else {
missingFields = missingFields + Const.COMMA + " " + key;
}
}
Logger.info("form errors size: " + targetForm.errors().size() + ", " + missingFields);
flash("message", "Please fill out all the required fields, marked with a red star. There are required fields in more than one tab. " +
"Missing fields are: " + missingFields);
return info();
}
DynamicForm requestData = Form.form().bindFromRequest();
String title = requestData.get(Const.TITLE);
Logger.info("form title: " + title);
Target target = new Target();
Target newTarget = new Target();
boolean isExisting = true;
try {
target = Target.findById(Long.valueOf(getFormParam(Const.NID)));
} catch (Exception e) {
Logger.info("is not existing exception");
isExisting = false;
}
if (getFormParam(Const.FIELD_WCT_ID) != null
&& (getFormParam(Const.FIELD_WCT_ID).equals("")
|| !Utils.isNumeric(getFormParam(Const.FIELD_WCT_ID)))) {
Logger.info("You may only enter a numeric ID in 'WCT ID'.");
flash("message", "You may only enter a numeric ID in 'WCT ID'.");
return info();
}
if (getFormParam(Const.FIELD_SPT_ID) != null && !getFormParam(Const.FIELD_SPT_ID).equals("")
&& !Utils.isNumeric(getFormParam(Const.FIELD_SPT_ID))) {
Logger.info("You may only enter a numeric ID in 'SPT ID'.");
flash("message", "You may only enter a numeric ID in 'SPT ID'.");
return info();
}
if (getFormParam(Const.LEGACY_SITE_ID) != null && !getFormParam(Const.LEGACY_SITE_ID).equals("")
&& !Utils.isNumeric(getFormParam(Const.LEGACY_SITE_ID))) {
Logger.info("You may only enter a numeric ID in 'LEGACY SITE ID'.");
flash("message", "You may only enter a numeric ID in 'LEGACY SITE ID'.");
return info();
}
if (target == null) {
target = new Target();
Logger.info("is not existing");
isExisting = false;
}
newTarget.nid = Target.createId();
newTarget.url = target.url;
newTarget.author = target.author;
if (target.author == null) {
newTarget.author = getFormParam(Const.USER);
}
newTarget.field_nominating_organisation = target.field_nominating_organisation;
newTarget.title = getFormParam(Const.TITLE);
newTarget.field_url = Scope.normalizeUrl(getFormParam(Const.FIELD_URL_NODE));
newTarget.field_key_site = Utils.getNormalizeBooleanString(getFormParam(Const.KEYSITE));
newTarget.field_description = getFormParam(Const.DESCRIPTION);
if (getFormParam(Const.FLAG_NOTES) != null) {
newTarget.flag_notes = getFormParam(Const.FLAG_NOTES);
}
if (getFormParam(Const.STATUS) != null) {
// Logger.info("status: " + getFormParam(Const.STATUS) + ".");
newTarget.status = Long.valueOf(getFormParam(Const.STATUS));
// Logger.info("status: " + newTarget.status + ".");
}
if (getFormParam(Const.QA_STATUS) != null) {
Logger.debug("### QA_STATUS");
newTarget.qa_status = getFormParam(Const.QA_STATUS);
CrawlPermissions.updateAllByTargetStatusChange(newTarget.field_url, newTarget.qa_status);
}
Logger.info("QA status: " + newTarget.qa_status + ", getFormParam(Const.QA_STATUS): " + getFormParam(Const.QA_STATUS));
if (getFormParam(Const.LANGUAGE) != null) {
// Logger.info("language: " + getFormParam(Const.LANGUAGE) + ".");
newTarget.language = getFormParam(Const.LANGUAGE);
}
if (getFormParam(Const.SELECTION_TYPE) != null) {
newTarget.selection_type = getFormParam(Const.SELECTION_TYPE);
}
if (getFormParam(Const.SELECTOR_NOTES) != null) {
newTarget.selector_notes = getFormParam(Const.SELECTOR_NOTES);
}
if (getFormParam(Const.ARCHIVIST_NOTES) != null) {
newTarget.archivist_notes = getFormParam(Const.ARCHIVIST_NOTES);
}
if (getFormParam(Const.LEGACY_SITE_ID) != null
&& getFormParam(Const.LEGACY_SITE_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.LEGACY_SITE_ID))) {
Logger.info("legacy site id: " + getFormParam(Const.LEGACY_SITE_ID) + ".");
newTarget.legacy_site_id = Long.valueOf(getFormParam(Const.LEGACY_SITE_ID));
}
Logger.info("authors: " + getFormParam(Const.AUTHORS) + ".");
if (getFormParam(Const.AUTHORS) != null) {
newTarget.authors = getFormParam(Const.AUTHORS);
}
if (getFormParam(Const.LIVE_SITE_STATUS) != null) {
newTarget.field_live_site_status = getFormParam(Const.LIVE_SITE_STATUS);
}
if (getFormParam(Const.FIELD_SUBJECT) != null) {
newTarget.field_subject = Utils.removeDuplicatesFromList(getFormParam(Const.FIELD_SUBJECT));
Logger.debug("newTarget.field_subject: " + newTarget.field_subject);
} else {
newTarget.field_subject = Const.NONE;
}
if (getFormParam(Const.TREE_KEYS) != null) {
newTarget.field_collection_categories = Utils.removeDuplicatesFromList(getFormParam(Const.TREE_KEYS));
Logger.debug("newTarget.field_collection_categories: " + newTarget.field_collection_categories);
}
if (getFormParam(Const.ORGANISATION) != null) {
if (!getFormParam(Const.ORGANISATION).toLowerCase().contains(Const.NONE)) {
Logger.info("nominating organisation: " + getFormParam(Const.ORGANISATION));
newTarget.field_nominating_organisation = Organisation.findByTitle(getFormParam(Const.ORGANISATION)).url;
} else {
newTarget.field_nominating_organisation = Const.NONE;
}
}
if (getFormParam(Const.ORIGINATING_ORGANISATION) != null) {
newTarget.originating_organisation = getFormParam(Const.ORIGINATING_ORGANISATION);
}
// Logger.info("author: " + getFormParam(Const.AUTHOR) + ", user: " + User.findByName(getFormParam(Const.AUTHOR)).url);
if (getFormParam(Const.AUTHOR) != null) {
newTarget.author = User.findByName(getFormParam(Const.AUTHOR)).url;
}
if (getFormParam(Const.TAGS) != null) {
if (!getFormParam(Const.TAGS).toLowerCase().contains(Const.NONE)) {
String[] tags = getFormParams(Const.TAGS);
String resTags = "";
for (String tag: tags)
{
if (tag != null && tag.length() > 0) {
Logger.info("add tag: " + tag);
resTags = resTags + Tag.findByName(tag).url + Const.LIST_DELIMITER;
}
}
newTarget.tags = resTags;
} else {
newTarget.tags = Const.NONE;
}
}
if (getFormParam(Const.FLAGS) != null) {
if (!getFormParam(Const.FLAGS).toLowerCase().contains(Const.NONE)) {
String[] flags = getFormParams(Const.FLAGS);
String resFlags = "";
for (String flag: flags)
{
if (flag != null && flag.length() > 0) {
Logger.info("add flag: " + flag);
String origFlag = Flags.getNameFromGuiName(flag);
Logger.info("original flag name: " + origFlag);
resFlags = resFlags + Flag.findByName(origFlag).url + Const.LIST_DELIMITER;
}
}
newTarget.flags = resFlags;
} else {
newTarget.flags = Const.NONE;
}
}
newTarget.justification = getFormParam(Const.JUSTIFICATION);
newTarget.summary = getFormParam(Const.SUMMARY);
newTarget.revision = getFormParam(Const.REVISION);
if (getFormParam(Const.FIELD_WCT_ID) != null
&& getFormParam(Const.FIELD_WCT_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.FIELD_WCT_ID))) {
newTarget.field_wct_id = Long.valueOf(getFormParam(Const.FIELD_WCT_ID));
}
if (getFormParam(Const.FIELD_SPT_ID) != null
&& getFormParam(Const.FIELD_SPT_ID).length() > 0
&& Utils.isNumeric(getFormParam(Const.FIELD_SPT_ID))) {
newTarget.field_spt_id = Long.valueOf(getFormParam(Const.FIELD_SPT_ID));
}
if (getFormParam(Const.FIELD_LICENSE) != null) {
if (!getFormParam(Const.FIELD_LICENSE).toLowerCase().contains(Const.NONE)) {
String[] licenses = getFormParams(Const.FIELD_LICENSE);
String resLicenses = "";
for (String curLicense: licenses)
{
if (curLicense != null && curLicense.length() > 0) {
Logger.info("add curLicense: " + curLicense);
if (curLicense.equals(Const.OPEN_UKWA_LICENSE)
&& getFormParam(Const.QA_STATUS) != null
&& !getFormParam(Const.QA_STATUS).equals(Const.CrawlPermissionStatus.GRANTED.name())) {
Logger.info("Saving is not allowed if License='Open UKWA License (2014-)' and Open UKWA License Requests status is anything other than 'Granted'.");
flash("message", "Saving is not allowed if License='Open UKWA License (2014-)' and Open UKWA License Requests status is anything other than 'Granted'.");
return info();
}
resLicenses = resLicenses + Taxonomy.findByFullNameExt(curLicense, Const.LICENCE).url + Const.LIST_DELIMITER;
}
}
newTarget.field_license = resLicenses;
} else {
newTarget.field_license = Const.NONE;
}
}
newTarget.field_uk_hosting = Target.checkUkHosting(newTarget.field_url);
Logger.debug("field_uk_hosting: " + newTarget.field_uk_hosting);
newTarget.field_uk_postal_address = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_UK_POSTAL_ADDRESS));
newTarget.field_uk_postal_address_url = getFormParam(Const.FIELD_UK_POSTAL_ADDRESS_URL);
Logger.debug("newTarget.field_uk_postal_address: " + newTarget.field_uk_postal_address);
if (newTarget.field_uk_postal_address
&& (newTarget.field_uk_postal_address_url == null || newTarget.field_uk_postal_address_url.length() == 0)) {
Logger.info("If UK Postal Address field has value 'Yes', the Postal Address URL is required.");
flash("message", "If UK Postal Address field has value 'Yes', the Postal Address URL is required.");
return info();
}
newTarget.field_via_correspondence = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_VIA_CORRESPONDENCE));
newTarget.value = getFormParam(Const.FIELD_NOTES);
if (newTarget.field_via_correspondence
&& (newTarget.value == null || newTarget.value.length() == 0)) {
Logger.info("If Via Correspondence field has value 'Yes', the Notes field is required.");
flash("message", "If Via Correspondence field has value 'Yes', the Notes field is required.");
return info();
}
newTarget.field_professional_judgement = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_PROFESSIONAL_JUDGEMENT));
newTarget.field_professional_judgement_exp = getFormParam(Const.FIELD_PROFESSIONAL_JUDGEMENT_EXP);
Logger.debug("newTarget.field_professional_judgement: " + newTarget.field_professional_judgement);
if (newTarget.field_professional_judgement
&& (newTarget.field_professional_judgement_exp == null || newTarget.field_professional_judgement_exp.length() == 0)) {
Logger.info("If Professional Judgement field has value 'Yes', the Professional Judgment Explanation field is required.");
flash("message", "If Professional Judgement field has value 'Yes', the Professional Judgment Explanation field is required.");
return info();
}
newTarget.field_no_ld_criteria_met = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_NO_LD_CRITERIA_MET));
// Logger.info("ignore robots: " + getFormParam(Const.FIELD_IGNORE_ROBOTS_TXT));
newTarget.field_ignore_robots_txt = Utils.getNormalizeBooleanString(getFormParam(Const.FIELD_IGNORE_ROBOTS_TXT));
if (getFormParam(Const.FIELD_CRAWL_START_DATE) != null) {
String startDateHumanView = getFormParam(Const.FIELD_CRAWL_START_DATE);
String startDateUnix = Utils.getUnixDateStringFromDate(startDateHumanView);
Logger.info("startDateHumanView: " + startDateHumanView + ", startDateUnix: " + startDateUnix);
newTarget.field_crawl_start_date = startDateUnix;
}
newTarget.date_of_publication = getFormParam(Const.DATE_OF_PUBLICATION);
newTarget.field_crawl_end_date = getFormParam(Const.FIELD_CRAWL_END_DATE);
if (getFormParam(Const.FIELD_CRAWL_END_DATE) != null) {
String endDateHumanView = getFormParam(Const.FIELD_CRAWL_END_DATE);
String endDateUnix = Utils.getUnixDateStringFromDate(endDateHumanView);
Logger.info("endDateHumanView: " + endDateHumanView + ", endDateUnix: " + endDateUnix);
newTarget.field_crawl_end_date = endDateUnix;
}
newTarget.white_list = getFormParam(Const.WHITE_LIST);
newTarget.black_list = getFormParam(Const.BLACK_LIST);
if (getFormParam(Const.FIELD_DEPTH) != null) {
newTarget.field_depth = Targets.getDepthNameFromGuiName(getFormParam(Const.FIELD_DEPTH));
}
newTarget.field_crawl_frequency = getFormParam(Const.FIELD_CRAWL_FREQUENCY);
if (getFormParam(Const.FIELD_SCOPE) != null) {
newTarget.field_scope = Targets.getScopeNameFromGuiName(getFormParam(Const.FIELD_SCOPE));
}
newTarget.keywords = getFormParam(Const.KEYWORDS);
newTarget.synonyms = getFormParam(Const.SYNONYMS);
newTarget.active = true;
long unixTime = System.currentTimeMillis() / 1000L;
String changedTime = String.valueOf(unixTime);
Logger.info("changed time: " + changedTime);
if (!isExisting) {
newTarget.url = Const.ACT_URL + newTarget.nid;
newTarget.edit_url = Const.WCT_URL + newTarget.nid;
} else {
target.active = false;
if (target.field_url != null) {
Logger.info("current target field_url: " + target.field_url);
target.domain = Scope.getDomainFromUrl(target.field_url);
}
target.changed = changedTime;
Logger.info("update target: " + target.nid + ", obj: " + target.toString());
boolean newScope = Target.isInScopeIp(target.field_url, target.url);
Scope.updateLookupEntry(target, newScope);
Ebean.update(target);
}
if (newTarget.field_url != null) {
Logger.info("current target field_url: " + newTarget.field_url);
newTarget.domain = Scope.getDomainFromUrl(newTarget.field_url);
}
newTarget.changed = changedTime;
if (newTarget.created == null || newTarget.created.length() == 0) {
newTarget.created = changedTime;
}
boolean newScope = Target.isInScopeIp(newTarget.field_url, newTarget.url);
Scope.updateLookupEntry(newTarget, newScope);
Ebean.save(newTarget);
Logger.info("save target: " + newTarget.toString());
res = redirect(routes.Targets.edit(newTarget.url));
} // end of save
if (delete != null) {
Long id = Long.valueOf(getFormParam(Const.NID));
Logger.info("deleting: " + id);
Target target = Target.findById(id);
Ebean.delete(target);
res = redirect(routes.Targets.index());
}
if (request != null) {
Logger.debug("request permission for title: " + getFormParam(Const.TITLE) +
" and target: " + getFormParam(Const.FIELD_URL_NODE));
if (getFormParam(Const.TITLE) != null && getFormParam(Const.FIELD_URL_NODE) != null) {
String name = getFormParam(Const.TITLE);
String target = Scope.normalizeUrl(getFormParam(Const.FIELD_URL_NODE));
res = redirect(routes.CrawlPermissions.licenceRequestForTarget(name, target));
}
}
if (archive != null) {
Logger.debug("archive target title: " + getFormParam(Const.TITLE) +
" with URL: " + getFormParam(Const.FIELD_URL_NODE));
if (getFormParam(Const.FIELD_URL_NODE) != null) {
String target = Scope.normalizeUrl(getFormParam(Const.FIELD_URL_NODE));
res = redirect(routes.TargetController.archiveTarget(target));
}
}
return res;
}
/**
* This method pushes a message onto a RabbitMQ queue for given target
* using global settings from project configuration file.
* @param target The field URL of the target
* @return
*/
public static Result archiveTarget(String target) {
Logger.debug("archiveTarget() " + target);
if (target != null && target.length() > 0) {
Properties props = System.getProperties();
Properties customProps = new Properties();
String queueHost = "";
String queuePort = "";
String queueName = "";
String routingKey= "";
String exchangeName = "";
try {
customProps.load(new FileInputStream(Const.PROJECT_PROPERTY_FILE));
for(String key : customProps.stringPropertyNames()) {
String value = customProps.getProperty(key);
// Logger.debug("archiveTarget() key: " + key + " => " + value);
if (key.equals(Const.QUEUE_HOST)) {
queueHost = value;
Logger.debug("archiveTarget() queue host: " + value);
}
if (key.equals(Const.QUEUE_PORT)) {
queuePort = value;
Logger.debug("archiveTarget() queue port: " + value);
}
if (key.equals(Const.QUEUE_NAME)) {
queueName = value;
Logger.debug("archiveTarget() queue name: " + value);
}
if (key.equals(Const.ROUTING_KEY)) {
routingKey = value;
Logger.debug("archiveTarget() routing key: " + value);
}
if (key.equals(Const.EXCHANGE_NAME)) {
exchangeName = value;
Logger.debug("archiveTarget() exchange name: " + value);
}
}
ConnectionFactory factory = new ConnectionFactory();
if (queueHost != null) {
factory.setHost(queueHost);
}
if (queuePort != null) {
factory.setPort(Integer.parseInt(queuePort));
}
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchangeName, "direct", true);
channel.queueDeclare(queueName, true, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey);
String message = target;
channel.basicPublish(exchangeName, routingKey, null, message.getBytes());
Logger.debug(" ### sent target '" + message + "' to queue");
channel.close();
connection.close();
} catch (IOException e) {
Logger.error("Target archiving error: " + e.getMessage());
return ok(infomessage.render("Target archiving error: " + e.getMessage()));
}
} else {
Logger.debug("Target field for archiving is empty");
return ok(infomessage.render("Target archiving error. Target field for archiving is empty"));
}
return ok(
ukwalicenceresult.render()
);
}
/**
* This method is checking scope for given URL and returns result in JSON format.
* @param url
* @return JSON result
* @throws WhoisException
*/
public static Result isInScope(String url) throws WhoisException {
// Logger.info("isInScope controller: " + url);
boolean res = Target.isInScope(url, null);
// Logger.info("isInScope res: " + res);
return ok(Json.toJson(res));
}
/**
* This method calculates collection children - objects that have parents.
* @param url The identifier for parent
* @param targetUrl This is an identifier for current target object
* @return child collection in JSON form
*/
public static String getChildren(String url, String targetUrl) {
// Logger.info("getChildren() target URL: " + targetUrl);
String res = "";
final StringBuffer sb = new StringBuffer();
sb.append(", \"children\":");
List<DCollection> childSuggestedCollections = DCollection.getChildLevelCollections(url);
if (childSuggestedCollections.size() > 0) {
sb.append(getTreeElements(childSuggestedCollections, targetUrl, false));
res = sb.toString();
// Logger.info("getChildren() res: " + res);
}
return res;
}
/**
* Mark collections that are stored in target object as selected
* @param collectionUrl The collection identifier
* @param targetUrl This is an identifier for current target object
* @return
*/
public static String checkSelection(String collectionUrl, String targetUrl) {
String res = "";
if (targetUrl != null && targetUrl.length() > 0) {
Target target = Target.findByUrl(targetUrl);
if (target.field_collection_categories != null &&
target.field_collection_categories.contains(collectionUrl)) {
res = "\"select\": true ,";
}
}
return res;
}
/**
* This method calculates first order collections.
* @param collectionList The list of all collections
* @param targetUrl This is an identifier for current target object
* @param parent This parameter is used to differentiate between root and children nodes
* @return collection object in JSON form
*/
public static String getTreeElements(List<DCollection> collectionList, String targetUrl, boolean parent) {
// Logger.info("getTreeElements() target URL: " + targetUrl);
String res = "";
if (collectionList.size() > 0) {
final StringBuffer sb = new StringBuffer();
sb.append("[");
Iterator<DCollection> itr = collectionList.iterator();
boolean firstTime = true;
while (itr.hasNext()) {
DCollection collection = itr.next();
// Logger.debug("add collection: " + collection.title + ", with url: " + collection.url +
// ", parent:" + collection.parent + ", parent size: " + collection.parent.length());
if ((parent && collection.parent.length() == 0) || !parent) {
if (firstTime) {
firstTime = false;
} else {
sb.append(", ");
}
// Logger.debug("added");
sb.append("{\"title\": \"" + collection.title + "\"," + checkSelection(collection.url, targetUrl) +
" \"key\": \"" + collection.url + "\"" +
getChildren(collection.url, targetUrl) + "}");
}
}
// Logger.info("collectionList level size: " + collectionList.size());
sb.append("]");
res = sb.toString();
// Logger.info("getTreeElements() res: " + res);
}
return res;
}
/**
* This method computes a tree of collections in JSON format.
* @param targetUrl This is an identifier for current target object
* @return tree structure
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result getSuggestedCollections(String targetUrl) {
Logger.info("getSuggestedCollections() target URL: " + targetUrl);
JsonNode jsonData = null;
final StringBuffer sb = new StringBuffer();
List<DCollection> suggestedCollections = DCollection.getFirstLevelCollections();
sb.append(getTreeElements(suggestedCollections, targetUrl, true));
// Logger.info("collections main level size: " + suggestedCollections.size());
jsonData = Json.toJson(Json.parse(sb.toString()));
// Logger.info("getCollections() json: " + jsonData.toString());
return ok(jsonData);
}
/**
* This method calculates subject children - objects that have parents.
* @param url The identifier for parent
* @param targetUrl This is an identifier for current target object
* @return child subject in JSON form
*/
public static String getSubjectChildren(String url, String targetUrl) {
// Logger.info("getSubjectChildren() target URL: " + targetUrl);
String res = "";
final StringBuffer sb = new StringBuffer();
sb.append(", \"children\":");
// List<Taxonomy> childSubject = Taxonomy.findListByType(Const.SUBSUBJECT);
Taxonomy subject = Taxonomy.findByUrl(url);
List<Taxonomy> childSubject = Taxonomy.findSubSubjectsList(subject.name);
if (childSubject.size() > 0) {
sb.append(getSubjectTreeElements(childSubject, targetUrl, false));
res = sb.toString();
// Logger.info("getSubjectChildren() res: " + res);
}
return res;
}
/**
* Mark subjects that are stored in target object as selected
* @param subjectUrl The subject identifier
* @param targetUrl This is an identifier for current target object
* @return
*/
public static String checkSubjectSelection(String subjectUrl, String targetUrl) {
String res = "";
if (targetUrl != null && targetUrl.length() > 0) {
Target target = Target.findByUrl(targetUrl);
if (target.field_subject != null &&
target.field_subject.contains(subjectUrl)) {
res = "\"select\": true ,";
}
}
return res;
}
/**
* Check if none value is selected
* @param subjectUrl The subject identifier
* @param targetUrl This is an identifier for current target object
* @return
*/
public static String checkNone(String targetUrl) {
String res = "";
if (targetUrl != null && targetUrl.length() > 0) {
Target target = Target.findByUrl(targetUrl);
if (target.field_subject != null
&& (target.field_subject.toLowerCase().contains(Const.NONE.toLowerCase()))) {
res = "\"select\": true ,";
}
}
return res;
}
/**
* This method calculates first order subjects.
* @param subjectList The list of all subjects
* @param targetUrl This is an identifier for current target object
* @param parent This parameter is used to differentiate between root and children nodes
* @return collection object in JSON form
*/
public static String getSubjectTreeElements(List<Taxonomy> subjectList, String targetUrl, boolean parent) {
// Logger.info("getSubjectTreeElements() target URL: " + targetUrl);
String res = "";
if (subjectList.size() > 0) {
final StringBuffer sb = new StringBuffer();
sb.append("[");
if (parent) {
sb.append("{\"title\": \"" + "None" + "\"," + checkNone(targetUrl) +
" \"key\": \"" + "None" + "\"" + "}, ");
}
Iterator<Taxonomy> itr = subjectList.iterator();
boolean firstTime = true;
while (itr.hasNext()) {
Taxonomy subject = itr.next();
// Logger.debug("add subject: " + subject.name + ", with url: " + subject.url +
// ", parent:" + subject.parent + ", parent size: " + subject.parent.length());
if ((parent && subject.parent.length() == 0) || !parent) {
if (firstTime) {
firstTime = false;
} else {
sb.append(", ");
}
// Logger.debug("added");
sb.append("{\"title\": \"" + subject.name + "\"," + checkSubjectSelection(subject.url, targetUrl) +
" \"key\": \"" + subject.url + "\"" +
getSubjectChildren(subject.url, targetUrl) + "}");
}
}
// Logger.info("subjectList level size: " + subjectList.size());
sb.append("]");
res = sb.toString();
// Logger.info("getSubjectTreeElements() res: " + res);
}
return res;
}
/**
* This method computes a tree of subjects in JSON format.
* @param targetUrl This is an identifier for current target object
* @return tree structure
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result getSubjectTree(String targetUrl) {
Logger.info("getSubjectTree() target URL: " + targetUrl);
JsonNode jsonData = null;
final StringBuffer sb = new StringBuffer();
List<Taxonomy> parentSubjects = Taxonomy.findListByTypeSorted(Const.SUBJECT);
// Logger.info("getSubjectTree() parentSubjects: " + parentSubjects.size());
sb.append(getSubjectTreeElements(parentSubjects, targetUrl, true));
// Logger.info("subjects main level size: " + parentSubjects.size());
jsonData = Json.toJson(Json.parse(sb.toString()));
// Logger.info("getSubjectTree() json: " + jsonData.toString());
return ok(jsonData);
}
}
| + fix for first level collections in Target edit.
| app/controllers/TargetController.java | + fix for first level collections in Target edit. | <ide><path>pp/controllers/TargetController.java
<ide> DCollection collection = itr.next();
<ide> // Logger.debug("add collection: " + collection.title + ", with url: " + collection.url +
<ide> // ", parent:" + collection.parent + ", parent size: " + collection.parent.length());
<del> if ((parent && collection.parent.length() == 0) || !parent) {
<add> if ((parent && collection.parent.length() == 0) || !parent || collection.parent.equals(Const.NONE_VALUE)) {
<ide> if (firstTime) {
<ide> firstTime = false;
<ide> } else {
<ide> final StringBuffer sb = new StringBuffer();
<ide> List<DCollection> suggestedCollections = DCollection.getFirstLevelCollections();
<ide> sb.append(getTreeElements(suggestedCollections, targetUrl, true));
<del>// Logger.info("collections main level size: " + suggestedCollections.size());
<add> Logger.info("collections main level size: " + suggestedCollections.size());
<ide> jsonData = Json.toJson(Json.parse(sb.toString()));
<del>// Logger.info("getCollections() json: " + jsonData.toString());
<add> Logger.info("getCollections() json: " + jsonData.toString());
<ide> return ok(jsonData);
<ide> }
<ide> |
|
Java | apache-2.0 | 7b1a78798b6a16d497f51d85a2b554bbbe5b72ed | 0 | RSDT/Japp16,RSDT/Japp,RSDT/Japp16 | package nl.rsdt.japp.application.fragments;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.overlay.infowindow.MarkerInfoWindow;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import nl.rsdt.japp.R;
import nl.rsdt.japp.application.Japp;
import nl.rsdt.japp.application.JappPreferences;
import nl.rsdt.japp.jotial.availability.StoragePermissionsChecker;
import nl.rsdt.japp.jotial.data.bodies.VosPostBody;
import nl.rsdt.japp.jotial.data.firebase.Location;
import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo;
import nl.rsdt.japp.jotial.data.structures.area348.UserInfo;
import nl.rsdt.japp.jotial.maps.NavigationLocationManager;
import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied;
import nl.rsdt.japp.jotial.maps.movement.MovementManager;
import nl.rsdt.japp.jotial.maps.pinning.Pin;
import nl.rsdt.japp.jotial.maps.pinning.PinningManager;
import nl.rsdt.japp.jotial.maps.pinning.PinningSession;
import nl.rsdt.japp.jotial.maps.sighting.SightingIcon;
import nl.rsdt.japp.jotial.maps.sighting.SightingSession;
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap;
import nl.rsdt.japp.jotial.maps.wrapper.IMarker;
import nl.rsdt.japp.jotial.maps.wrapper.IPolygon;
import nl.rsdt.japp.jotial.maps.wrapper.google.GoogleJotiMap;
import nl.rsdt.japp.jotial.maps.wrapper.osm.OsmJotiMap;
import nl.rsdt.japp.jotial.navigation.NavigationSession;
import nl.rsdt.japp.jotial.net.apis.AutoApi;
import nl.rsdt.japp.jotial.net.apis.UserApi;
import nl.rsdt.japp.jotial.net.apis.VosApi;
import nl.rsdt.japp.service.LocationService;
import nl.rsdt.japp.service.ServiceManager;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 8-7-2016
* Description...
*/
public class JappMapFragment extends Fragment implements IJotiMap.OnMapReadyCallback, SharedPreferences.OnSharedPreferenceChangeListener{
public static final String TAG = "JappMapFragment";
private static final String BUNDLE_MAP = "BUNDLE_MAP";
private static final String BUNDLE_OSM_ACTIVE = "BUNDLE_OSM_ACTIVE_B";
private static final String OSM_ZOOM = "OSM_ZOOM";
private static final String OSM_LAT = "OSM_LAT";
private static final java.lang.String OSM_LNG = "OSM_LNG";
private static final String OSM_OR = "OSM_OR";
private static final String OSM_BUNDLE = "OSM_BUNDLE";
private ServiceManager<LocationService, LocationService.LocationBinder> serviceManager = new ServiceManager<>(LocationService.class);
private IJotiMap jotiMap;
private MapView googleMapView;
private NavigationLocationManager navigationLocationManager ;
public IJotiMap getJotiMap() {
return jotiMap;
}
private IJotiMap.OnMapReadyCallback callback;
private PinningManager pinningManager = new PinningManager();
private MovementManager movementManager = new MovementManager();
private HashMap<String, IPolygon> areas = new HashMap<>();
private boolean osmActive = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
navigationLocationManager = new NavigationLocationManager();
JappPreferences.getVisiblePreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pinningManager.intialize(getActivity());
pinningManager.onCreate(savedInstanceState);
movementManager.onCreate(savedInstanceState);
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_map, container, false);
return createMap(savedInstanceState, v);
}
private View createMap(Bundle savedInstanceState, View v){
boolean useOSM = JappPreferences.useOSM();
View view;
if (useOSM){
view = createOSMMap(savedInstanceState, v);
}else {
view = createGoogleMap(savedInstanceState, v);
}
FloatingActionMenu menu = (FloatingActionMenu) view.findViewById(R.id.fab_menu);
menu.bringToFront();
return view;
}
private View createOSMMap(Bundle savedInstanceState, View v) {
StoragePermissionsChecker.check(getActivity());
osmActive = true;
org.osmdroid.views.MapView osmView = new org.osmdroid.views.MapView(getActivity());
((ViewGroup)v).addView(osmView);
Context ctx = getActivity().getApplication();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
switch (JappPreferences.getOsmMapSource()){
case Mapnik:
osmView.setTileSource(TileSourceFactory.MAPNIK);
break;
case OpenSeaMap:
osmView.setTileSource(TileSourceFactory.OPEN_SEAMAP);
break;
case HikeBike:
osmView.setTileSource(TileSourceFactory.HIKEBIKEMAP);
break;
case OpenTopo:
osmView.setTileSource(TileSourceFactory.OpenTopo);
break;
case Fiets_NL:
osmView.setTileSource(TileSourceFactory.FIETS_OVERLAY_NL);
break;
case Default:
osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
break;
case CloudMade_Normal:
osmView.setTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES);
break;
case CloudMade_Small:
osmView.setTileSource(TileSourceFactory.CLOUDMADESMALLTILES);
break;
case ChartBundle_ENRH:
osmView.setTileSource(TileSourceFactory.ChartbundleENRH);
break;
case ChartBundle_ENRL:
osmView.setTileSource(TileSourceFactory.ChartbundleENRH);
break;
case ChartBundle_WAC:
osmView.setTileSource(TileSourceFactory.ChartbundleWAC);
break;
case USGS_Sat:
osmView.setTileSource(TileSourceFactory.USGS_SAT);
break;
case USGS_Topo:
osmView.setTileSource(TileSourceFactory.USGS_TOPO);
break;
case Public_Transport:
osmView.setTileSource(TileSourceFactory.PUBLIC_TRANSPORT);
break;
case Road_NL:
osmView.setTileSource(TileSourceFactory.ROADS_OVERLAY_NL);
break;
case Base_NL:
osmView.setTileSource(TileSourceFactory.BASE_OVERLAY_NL);
break;
default:
osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
break;
}
osmView.getController().setCenter(new GeoPoint(51.958852, 5.954517));
osmView.getController().setZoom(11);
osmView.setBuiltInZoomControls(true);
osmView.setMultiTouchControls(true);
osmView.setFlingEnabled(true);
osmView.setTilesScaledToDpi(true);
if (savedInstanceState != null) {
Bundle osmbundle = savedInstanceState.getBundle(OSM_BUNDLE);
if (osmbundle != null) {
osmView.getController().setZoom(osmbundle.getInt(OSM_ZOOM));
osmView.getController().setCenter(new GeoPoint(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG)));
osmView.setRotation(osmbundle.getFloat(OSM_OR));
}
}
movementManager.setSnackBarView(osmView);
setupHuntButton(v).setEnabled(true);
setupSpotButton(v).setEnabled(true);
setupPinButton(v).setEnabled(true);
setupFollowButton(v);
setupNavigationButton(v);
jotiMap = OsmJotiMap.getJotiMapInstance(osmView);
return v;
}
private View createGoogleMap(Bundle savedInstanceState, View v){
osmActive = false;
googleMapView = new MapView(getActivity());
((ViewGroup)v).addView(googleMapView);
Context ctx = getActivity().getApplication();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
if(savedInstanceState != null)
{
if(savedInstanceState.containsKey(BUNDLE_MAP)) {
googleMapView.onCreate(savedInstanceState.getBundle(BUNDLE_MAP));
} else {
googleMapView.onCreate(null);
}
} else
{
googleMapView.onCreate(null);
}
movementManager.setSnackBarView(googleMapView);
setupHuntButton(v);
setupSpotButton(v);
setupPinButton(v);
setupFollowButton(v);
setupNavigationButton(v);
jotiMap = GoogleJotiMap.getJotiMapInstance(googleMapView);
if(savedInstanceState != null) {
Bundle osmbundle = savedInstanceState.getBundle(OSM_BUNDLE);
if (osmbundle != null) {
jotiMap.setPreviousZoom(osmbundle.getInt(OSM_ZOOM));
jotiMap.setPreviousCameraPosition(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG));
jotiMap.setPreviousRotation(osmbundle.getFloat(OSM_OR));
}
}
return v;
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
movementManager.onSaveInstanceState(savedInstanceState);
pinningManager.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(BUNDLE_OSM_ACTIVE, osmActive);
if (!osmActive) {
Bundle mapBundle = new Bundle();
googleMapView.onSaveInstanceState(mapBundle);
savedInstanceState.putBundle(BUNDLE_MAP, mapBundle);
}else if (jotiMap instanceof OsmJotiMap){
org.osmdroid.views.MapView osmMap = ((OsmJotiMap) jotiMap).getOSMMap();
Bundle osmMapBundle = new Bundle();
osmMapBundle.putInt(OSM_ZOOM, osmMap.getZoomLevel());
osmMapBundle.putDouble(OSM_LAT, osmMap.getMapCenter().getLatitude());
osmMapBundle.putDouble(OSM_LNG, osmMap.getMapCenter().getLongitude());
osmMapBundle.putFloat(OSM_OR, osmMap.getMapOrientation());
savedInstanceState.putBundle(OSM_BUNDLE, osmMapBundle);
}
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void getMapAsync(IJotiMap.OnMapReadyCallback callback) {
jotiMap.getMapAsync(this);
this.callback = callback;
}
public void onStart() {
super.onStart();
if (!osmActive) {
googleMapView.onStart();
}
}
public void onStop() {
super.onStop();
if (!osmActive) {
googleMapView.onStop();
}
}
@Override
public void onResume() {
super.onResume();
if (!osmActive) {
googleMapView.onResume();
}else {
Configuration.getInstance().load(getActivity(), PreferenceManager.getDefaultSharedPreferences(getActivity()));
}
serviceManager.add(movementManager);
movementManager.onResume();
if(!serviceManager.isBound()) {
serviceManager.bind(this.getActivity());
}
}
@Override
public void onPause() {
super.onPause();
if (!osmActive && googleMapView != null) {
googleMapView.onPause();
}
movementManager.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (!osmActive) {
googleMapView.onDestroy();
}
if(movementManager != null) {
movementManager.onDestroy();
serviceManager.remove(movementManager);
movementManager = null;
}
JappPreferences.getVisiblePreferences().registerOnSharedPreferenceChangeListener(this);
serviceManager.unbind(getActivity());
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (!osmActive) {
googleMapView.onLowMemory();
}
}
public void onMapReady(IJotiMap jotiMap){
this.jotiMap = jotiMap;
jotiMap.clear();
movementManager.onMapReady(jotiMap);
setupDeelgebieden();
pinningManager.onMapReady(jotiMap);
if(callback != null)
{
callback.onMapReady(jotiMap);
}
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(0,0))
.visible(true);
Bitmap icon = null;
final IMarker marker = jotiMap.addMarker(new Pair<MarkerOptions, Bitmap>(markerOptions, icon));
navigationLocationManager.setCallback(new NavigationLocationManager.OnNewLocation() {
@Override
public void onNewLocation(Location location) {
marker.setPosition(new LatLng(location.lat,location.lon));
}
@Override
public void onNotInCar() {
marker.setPosition(new LatLng(0,0));
}
});
}
private void setupDeelgebieden() {
Set<String> enabled = JappPreferences.getAreasEnabled();
for(String area : enabled) {
if(!areas.containsKey(area)) {
setupDeelgebied(Deelgebied.parse(area));
}
}
if(jotiMap instanceof OsmJotiMap) {
((OsmJotiMap) jotiMap).getOSMMap().invalidate();
}
}
public void setupDeelgebied(Deelgebied deelgebied) {
if(!deelgebied.getCoordinates().isEmpty()) {
PolygonOptions options = new PolygonOptions().addAll(deelgebied.getCoordinates());
if(JappPreferences.getAreasColorEnabled()) {
int alphaPercent = JappPreferences.getAreasColorAlpha();
float alpha = ((float)(100 - alphaPercent))/100 * 255;
options.fillColor(deelgebied.alphaled(Math.round(alpha)));
} else {
options.fillColor(Color.TRANSPARENT);
}
options.strokeColor(deelgebied.getColor());
if(JappPreferences.getAreasEdgesEnabled()) {
options.strokeWidth(JappPreferences.getAreasEdgesWidth());
} else {
options.strokeWidth(0);
}
options.visible(true);
areas.put(deelgebied.getName(), jotiMap.addPolygon(options));
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
IPolygon polygon;
switch (key){
case JappPreferences.USE_OSM:
break;
case JappPreferences.AREAS:
if(jotiMap == null) break;
Set<String> enabled = JappPreferences.getAreasEnabled();
for(String area : enabled) {
if(!areas.containsKey(area)) {
setupDeelgebied(Deelgebied.parse(area));
}
}
List<String> toBeRemoved = new ArrayList<>();
for(String area : areas.keySet()) {
if(!enabled.contains(area)) {
IPolygon poly = areas.get(area);
poly.remove();
toBeRemoved.add(area);
}
}
for(String area : toBeRemoved) {
areas.remove(area);
}
if(jotiMap instanceof OsmJotiMap) {
((OsmJotiMap) jotiMap).getOSMMap().invalidate();
}
break;
case JappPreferences.AREAS_EDGES:
boolean edges = JappPreferences.getAreasEdgesEnabled();
for(HashMap.Entry<String, IPolygon> pair : areas.entrySet()){
polygon = pair.getValue();
if(edges) {
polygon.setStrokeWidth(JappPreferences.getAreasEdgesWidth());
} else {
polygon.setStrokeWidth(0);
}
}
break;
case JappPreferences.AREAS_EDGES_WIDTH:
boolean edgesEnabled = JappPreferences.getAreasEdgesEnabled();
for(HashMap.Entry<String, IPolygon> pair : areas.entrySet()){
polygon = pair.getValue();
if(edgesEnabled) {
polygon.setStrokeWidth(JappPreferences.getAreasEdgesWidth());
}
}
break;
case JappPreferences.AREAS_COLOR:
boolean color = JappPreferences.getAreasColorEnabled();
for(HashMap.Entry<String, IPolygon> pair : areas.entrySet()){
polygon = pair.getValue();
if(color) {
int alphaPercent = JappPreferences.getAreasColorAlpha();
float alpha = ((float)(100 - alphaPercent))/100 * 255;
polygon.setFillColor(Deelgebied.parse(pair.getKey()).alphaled(Math.round(alpha)));
} else {
polygon.setFillColor(Color.TRANSPARENT);
}
}
break;
case JappPreferences.AREAS_COLOR_ALPHA:
boolean areasColorEnabled = JappPreferences.getAreasColorEnabled();
for(HashMap.Entry<String, IPolygon> pair : areas.entrySet()){
polygon = pair.getValue();
if(areasColorEnabled) {
int alphaPercent = JappPreferences.getAreasColorAlpha();
float alpha = ((float)(100 - alphaPercent))/100 * 255;
polygon.setFillColor(Deelgebied.parse(pair.getKey()).alphaled(Math.round(alpha)));
}
}
break;
}
}
public FloatingActionButton setupSpotButton(View v) {
FloatingActionButton spotButton = (FloatingActionButton)v.findViewById(R.id.fab_spot);
spotButton.setOnClickListener(new View.OnClickListener() {
SightingSession session;
@Override
public void onClick(View view) {
/*--- Hide the menu ---*/
View v = getView();
FloatingActionMenu menu = (FloatingActionMenu)v.findViewById(R.id.fab_menu);
menu.hideMenu(true);
/*--- Build a SightingSession and start it ---*/
session = new SightingSession.Builder()
.setType(SightingSession.SIGHT_SPOT)
.setGoogleMap(jotiMap)
.setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container))
.setDialogContext(JappMapFragment.this.getActivity())
.setOnSightingCompletedCallback(new SightingSession.OnSightingCompletedCallback() {
@Override
public void onSightingCompleted(LatLng chosen, Deelgebied deelgebied, String optionalInfo) {
/*--- Show the menu ---*/
FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu);
menu.showMenu(true);
if(chosen != null)
{
/*--- Construct a JSON string with the data ---*/
VosPostBody builder = VosPostBody.getDefault();
builder.setIcon(SightingIcon.SPOT);
builder.setLatLng(chosen);
builder.setTeam(deelgebied.getName().substring(0, 1));
builder.setInfo(optionalInfo);
VosApi api = Japp.getApi(VosApi.class);
api.post(builder).enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
switch (response.code()) {
case 200:
Snackbar.make(snackbarView, "Succesvol verzonden", Snackbar.LENGTH_LONG).show();
break;
case 404:
Snackbar.make(snackbarView, "Verkeerde gegevens", Snackbar.LENGTH_LONG).show();
break;
default:
Snackbar.make(snackbarView, "Probleem bij verzenden: " + response.code(), Snackbar.LENGTH_LONG).show();
break;
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
Snackbar.make(snackbarView, "Probleem bij verzenden: " + t.toString() , Snackbar.LENGTH_LONG).show();
}
});
/**
* TODO: send details?
* Log the spot in firebase.
* */
Japp.getAnalytics().logEvent("EVENT_SPOT", new Bundle());
}
session = null;
}
})
.create();
session.start();
}
});
return spotButton;
}
public FloatingActionButton setupFollowButton(View v) {
FloatingActionButton followButton = (FloatingActionButton) v.findViewById(R.id.fab_follow);
followButton.setOnClickListener(new View.OnClickListener() {
MovementManager.FollowSession session;
@Override
public void onClick(View view) {
View v = getView();
FloatingActionButton followButton = (FloatingActionButton) v.findViewById(R.id.fab_follow);
/*--- Hide the menu ---*/
FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu);
/**
* TODO: use color to identify follow state?
* */
if (session != null) {
// followButton.setColorNormal(Color.parseColor("#DA4336"));
followButton.setLabelText("Volg mij");
session.end();
session = null;
} else {
menu.close(true);
//followButton.setColorNormal(Color.parseColor("#5cd65c"));
followButton.setLabelText("Stop volgen");
session = movementManager.newSession(jotiMap.getPreviousCameraPosition(), JappPreferences.getFollowZoom(), JappPreferences.getFollowAngleOfAttack());
}
}
});
return followButton;
}
private FloatingActionButton setupPinButton(View v) {
FloatingActionButton pinButton = (FloatingActionButton)v.findViewById(R.id.fab_mark);
pinButton.setOnClickListener(new View.OnClickListener() {
PinningSession session;
@Override
public void onClick(View view) {
View v = getView();
FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu);
if(session != null) {
/*--- Show the menu ---*/
menu.showMenu(true);
session.end();
session = null;
} else {
/*--- Hide the menu ---*/
menu.hideMenu(true);
session = new PinningSession.Builder()
.setJotiMap(jotiMap)
.setCallback(new PinningSession.OnPinningCompletedCallback() {
@Override
public void onPinningCompleted(Pin pin) {
if(pin != null) {
pinningManager.add(pin);
}
FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu);
menu.showMenu(true);
session.end();
session = null;
}
})
.setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container))
.setDialogContext(JappMapFragment.this.getActivity())
.create();
session.start();
}
}
});
return pinButton;
}
private FloatingActionButton setupNavigationButton(View v) {
FloatingActionButton navigationButton = (FloatingActionButton)v.findViewById(R.id.fab_nav);
navigationButton.setOnClickListener(new View.OnClickListener() {
NavigationSession session;
@Override
public void onClick(View view) {
View v = getView();
FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu);
if(session != null) {
/*--- Show the menu ---*/
menu.showMenu(true);
session.end();
session = null;
} else {
/*--- Hide the menu ---*/
menu.hideMenu(true);
session = new NavigationSession.Builder()
.setJotiMap(jotiMap)
.setCallback(new NavigationSession.OnNavigationCompletedCallback() {
@Override
public void onNavigationCompleted(final LatLng navigateTo, boolean toNavigationPhone) {
FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu);
menu.showMenu(true);
session.end();
session = null;
if (navigateTo != null) {
if (!toNavigationPhone) {
try{
switch(JappPreferences.navigationApp()){
case GoogleMaps:
String uristr = "google.navigation:q=" + Double.toString(navigateTo.latitude) + "," + Double.toString(navigateTo.longitude);
Uri gmmIntentUri = Uri.parse(uristr);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
break;
case Waze:
String uri = "waze://?ll="+Double.toString(navigateTo.latitude) +","+Double.toString(navigateTo.longitude) +"&navigate=yes";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
break;
}
} catch (ActivityNotFoundException e){
System.out.println(e.toString());
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
Snackbar.make(snackbarView, "De App: " + JappPreferences.navigationApp().toString() +" is niet geinstaleerd.", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string
}
}else{
int id = JappPreferences.getAccountId();
if (id >= 0) {
final AutoApi autoApi = Japp.getApi(AutoApi.class);
autoApi.getInfoById(JappPreferences.getAccountKey(), id).enqueue(new Callback<AutoInzittendeInfo>() {
@Override
public void onResponse(Call<AutoInzittendeInfo> call, Response<AutoInzittendeInfo> response) {
if (response.code() == 200) {
AutoInzittendeInfo autoInfo = response.body();
if (autoInfo != null) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(NavigationLocationManager.FDB_NAME + "/" + autoInfo.autoEigenaar);
ref.setValue(new Location(navigateTo, JappPreferences.getAccountUsername()));
}
}
if (response.code() == 404){
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
Snackbar.make(snackbarView, "Fout: plaats jezelf eerst in een auto via telegram.", Snackbar.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<AutoInzittendeInfo> call, Throwable t) {
}
});
}
}
}
}
})
.setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container))
.setDialogContext(JappMapFragment.this.getActivity())
.create();
session.start();
}
}
});
return navigationButton;
}
private FloatingActionButton setupHuntButton(View v){
FloatingActionButton huntButton = (FloatingActionButton)v.findViewById(R.id.fab_hunt);
huntButton.setOnClickListener(new View.OnClickListener() {
SightingSession session;
@Override
public void onClick(View view) {
/*--- Hide the menu ---*/
View v = getView();
FloatingActionMenu menu = (FloatingActionMenu)v.findViewById(R.id.fab_menu);
menu.hideMenu(true);
/*--- Build a SightingSession and start it ---*/
session = new SightingSession.Builder()
.setType(SightingSession.SIGHT_HUNT)
.setGoogleMap(jotiMap)
.setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container))
.setDialogContext(JappMapFragment.this.getActivity())
.setOnSightingCompletedCallback(new SightingSession.OnSightingCompletedCallback() {
@Override
public void onSightingCompleted(LatLng chosen, Deelgebied deelgebied, String optionalInfo) {
/*--- Show the menu ---*/
FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu);
menu.showMenu(true);
if(chosen != null)
{
/*--- Construct a JSON string with the data ---*/
VosPostBody builder = VosPostBody.getDefault();
builder.setIcon(SightingIcon.HUNT);
builder.setLatLng(chosen);
builder.setTeam(deelgebied.getName().substring(0, 1));
builder.setInfo(optionalInfo);
VosApi api = Japp.getApi(VosApi.class);
api.post(builder).enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
switch (response.code()) {
case 200:
Snackbar.make(snackbarView, "Succesvol verzonden", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string
break;
case 404:
Snackbar.make(snackbarView, "Verkeerde gegevens", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string
break;
default:
Snackbar.make(snackbarView, "Probleem bij verzenden: " + response.code(), Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string
break;
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
Snackbar.make(snackbarView, "Probleem bij verzenden: " + t.toString() , Snackbar.LENGTH_LONG).show();//// TODO: 08/08/17 magic string
}
});
/**
* TODO: send details?
* Log the hunt in firebase.
* */
Japp.getAnalytics().logEvent("EVENT_HUNT", new Bundle()); //// TODO: 08/08/17 magic string
}
}
})
.create();
session.start();
}
});
return huntButton;
}
}
| app/src/main/java/nl/rsdt/japp/application/fragments/JappMapFragment.java | package nl.rsdt.japp.application.fragments;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.overlay.infowindow.MarkerInfoWindow;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import nl.rsdt.japp.R;
import nl.rsdt.japp.application.Japp;
import nl.rsdt.japp.application.JappPreferences;
import nl.rsdt.japp.jotial.availability.StoragePermissionsChecker;
import nl.rsdt.japp.jotial.data.bodies.VosPostBody;
import nl.rsdt.japp.jotial.data.firebase.Location;
import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo;
import nl.rsdt.japp.jotial.data.structures.area348.UserInfo;
import nl.rsdt.japp.jotial.maps.NavigationLocationManager;
import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied;
import nl.rsdt.japp.jotial.maps.movement.MovementManager;
import nl.rsdt.japp.jotial.maps.pinning.Pin;
import nl.rsdt.japp.jotial.maps.pinning.PinningManager;
import nl.rsdt.japp.jotial.maps.pinning.PinningSession;
import nl.rsdt.japp.jotial.maps.sighting.SightingIcon;
import nl.rsdt.japp.jotial.maps.sighting.SightingSession;
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap;
import nl.rsdt.japp.jotial.maps.wrapper.IMarker;
import nl.rsdt.japp.jotial.maps.wrapper.IPolygon;
import nl.rsdt.japp.jotial.maps.wrapper.google.GoogleJotiMap;
import nl.rsdt.japp.jotial.maps.wrapper.osm.OsmJotiMap;
import nl.rsdt.japp.jotial.navigation.NavigationSession;
import nl.rsdt.japp.jotial.net.apis.AutoApi;
import nl.rsdt.japp.jotial.net.apis.UserApi;
import nl.rsdt.japp.jotial.net.apis.VosApi;
import nl.rsdt.japp.service.LocationService;
import nl.rsdt.japp.service.ServiceManager;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 8-7-2016
* Description...
*/
public class JappMapFragment extends Fragment implements IJotiMap.OnMapReadyCallback, SharedPreferences.OnSharedPreferenceChangeListener{
public static final String TAG = "JappMapFragment";
private static final String BUNDLE_MAP = "BUNDLE_MAP";
private static final String BUNDLE_OSM_ACTIVE = "BUNDLE_OSM_ACTIVE_B";
private static final String OSM_ZOOM = "OSM_ZOOM";
private static final String OSM_LAT = "OSM_LAT";
private static final java.lang.String OSM_LNG = "OSM_LNG";
private static final String OSM_OR = "OSM_OR";
private static final String OSM_BUNDLE = "OSM_BUNDLE";
private ServiceManager<LocationService, LocationService.LocationBinder> serviceManager = new ServiceManager<>(LocationService.class);
private IJotiMap jotiMap;
private MapView googleMapView;
private NavigationLocationManager navigationLocationManager ;
public IJotiMap getJotiMap() {
return jotiMap;
}
private IJotiMap.OnMapReadyCallback callback;
private PinningManager pinningManager = new PinningManager();
private MovementManager movementManager = new MovementManager();
private HashMap<String, IPolygon> areas = new HashMap<>();
private boolean osmActive = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
navigationLocationManager = new NavigationLocationManager();
JappPreferences.getVisiblePreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pinningManager.intialize(getActivity());
pinningManager.onCreate(savedInstanceState);
movementManager.onCreate(savedInstanceState);
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_map, container, false);
return createMap(savedInstanceState, v);
}
private View createMap(Bundle savedInstanceState, View v){
boolean useOSM = JappPreferences.useOSM();
View view;
if (useOSM){
view = createOSMMap(savedInstanceState, v);
}else {
view = createGoogleMap(savedInstanceState, v);
}
FloatingActionMenu menu = (FloatingActionMenu) view.findViewById(R.id.fab_menu);
menu.bringToFront();
return view;
}
private View createOSMMap(Bundle savedInstanceState, View v) {
StoragePermissionsChecker.check(getActivity());
osmActive = true;
org.osmdroid.views.MapView osmView = new org.osmdroid.views.MapView(getActivity());
((ViewGroup)v).addView(osmView);
Context ctx = getActivity().getApplication();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
switch (JappPreferences.getOsmMapSource()){
case Mapnik:
osmView.setTileSource(TileSourceFactory.MAPNIK);
break;
case OpenSeaMap:
osmView.setTileSource(TileSourceFactory.OPEN_SEAMAP);
break;
case HikeBike:
osmView.setTileSource(TileSourceFactory.HIKEBIKEMAP);
break;
case OpenTopo:
osmView.setTileSource(TileSourceFactory.OpenTopo);
break;
case Fiets_NL:
osmView.setTileSource(TileSourceFactory.FIETS_OVERLAY_NL);
break;
case Default:
osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
break;
case CloudMade_Normal:
osmView.setTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES);
break;
case CloudMade_Small:
osmView.setTileSource(TileSourceFactory.CLOUDMADESMALLTILES);
break;
case ChartBundle_ENRH:
osmView.setTileSource(TileSourceFactory.ChartbundleENRH);
break;
case ChartBundle_ENRL:
osmView.setTileSource(TileSourceFactory.ChartbundleENRH);
break;
case ChartBundle_WAC:
osmView.setTileSource(TileSourceFactory.ChartbundleWAC);
break;
case USGS_Sat:
osmView.setTileSource(TileSourceFactory.USGS_SAT);
break;
case USGS_Topo:
osmView.setTileSource(TileSourceFactory.USGS_TOPO);
break;
case Public_Transport:
osmView.setTileSource(TileSourceFactory.PUBLIC_TRANSPORT);
break;
case Road_NL:
osmView.setTileSource(TileSourceFactory.ROADS_OVERLAY_NL);
break;
case Base_NL:
osmView.setTileSource(TileSourceFactory.BASE_OVERLAY_NL);
break;
default:
osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
break;
}
osmView.getController().setCenter(new GeoPoint(51.958852, 5.954517));
osmView.getController().setZoom(11);
osmView.setBuiltInZoomControls(true);
osmView.setMultiTouchControls(true);
osmView.setFlingEnabled(true);
osmView.setTilesScaledToDpi(true);
if (savedInstanceState != null) {
Bundle osmbundle = savedInstanceState.getBundle(OSM_BUNDLE);
if (osmbundle != null) {
osmView.getController().setZoom(osmbundle.getInt(OSM_ZOOM));
osmView.getController().setCenter(new GeoPoint(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG)));
osmView.setRotation(osmbundle.getFloat(OSM_OR));
}
}
movementManager.setSnackBarView(osmView);
setupHuntButton(v).setEnabled(true);
setupSpotButton(v).setEnabled(true);
setupPinButton(v).setEnabled(true);
setupFollowButton(v);
setupNavigationButton(v);
jotiMap = OsmJotiMap.getJotiMapInstance(osmView);
return v;
}
private View createGoogleMap(Bundle savedInstanceState, View v){
osmActive = false;
googleMapView = new MapView(getActivity());
((ViewGroup)v).addView(googleMapView);
Context ctx = getActivity().getApplication();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
if(savedInstanceState != null)
{
if(savedInstanceState.containsKey(BUNDLE_MAP)) {
googleMapView.onCreate(savedInstanceState.getBundle(BUNDLE_MAP));
} else {
googleMapView.onCreate(null);
}
} else
{
googleMapView.onCreate(null);
}
movementManager.setSnackBarView(googleMapView);
setupHuntButton(v);
setupSpotButton(v);
setupPinButton(v);
setupFollowButton(v);
setupNavigationButton(v);
jotiMap = GoogleJotiMap.getJotiMapInstance(googleMapView);
if(savedInstanceState != null) {
Bundle osmbundle = savedInstanceState.getBundle(OSM_BUNDLE);
if (osmbundle != null) {
jotiMap.setPreviousZoom(osmbundle.getInt(OSM_ZOOM));
jotiMap.setPreviousCameraPosition(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG));
jotiMap.setPreviousRotation(osmbundle.getFloat(OSM_OR));
}
}
return v;
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
movementManager.onSaveInstanceState(savedInstanceState);
pinningManager.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(BUNDLE_OSM_ACTIVE, osmActive);
if (!osmActive) {
Bundle mapBundle = new Bundle();
googleMapView.onSaveInstanceState(mapBundle);
savedInstanceState.putBundle(BUNDLE_MAP, mapBundle);
}else if (jotiMap instanceof OsmJotiMap){
org.osmdroid.views.MapView osmMap = ((OsmJotiMap) jotiMap).getOSMMap();
Bundle osmMapBundle = new Bundle();
osmMapBundle.putInt(OSM_ZOOM, osmMap.getZoomLevel());
osmMapBundle.putDouble(OSM_LAT, osmMap.getMapCenter().getLatitude());
osmMapBundle.putDouble(OSM_LNG, osmMap.getMapCenter().getLongitude());
osmMapBundle.putFloat(OSM_OR, osmMap.getMapOrientation());
savedInstanceState.putBundle(OSM_BUNDLE, osmMapBundle);
}
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void getMapAsync(IJotiMap.OnMapReadyCallback callback) {
jotiMap.getMapAsync(this);
this.callback = callback;
}
public void onStart() {
super.onStart();
if (!osmActive) {
googleMapView.onStart();
}
}
public void onStop() {
super.onStop();
if (!osmActive) {
googleMapView.onStop();
}
}
@Override
public void onResume() {
super.onResume();
if (!osmActive) {
googleMapView.onResume();
}else {
Configuration.getInstance().load(getActivity(), PreferenceManager.getDefaultSharedPreferences(getActivity()));
}
serviceManager.add(movementManager);
movementManager.onResume();
if(!serviceManager.isBound()) {
serviceManager.bind(this.getActivity());
}
}
@Override
public void onPause() {
super.onPause();
if (!osmActive && googleMapView != null) {
googleMapView.onPause();
}
movementManager.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
if (!osmActive) {
googleMapView.onDestroy();
}
if(movementManager != null) {
movementManager.onDestroy();
serviceManager.remove(movementManager);
movementManager = null;
}
JappPreferences.getVisiblePreferences().registerOnSharedPreferenceChangeListener(this);
serviceManager.unbind(getActivity());
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (!osmActive) {
googleMapView.onLowMemory();
}
}
public void onMapReady(IJotiMap jotiMap){
this.jotiMap = jotiMap;
jotiMap.clear();
movementManager.onMapReady(jotiMap);
setupDeelgebieden();
pinningManager.onMapReady(jotiMap);
if(callback != null)
{
callback.onMapReady(jotiMap);
}
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(0,0))
.visible(true);
Bitmap icon = null;
final IMarker marker = jotiMap.addMarker(new Pair<MarkerOptions, Bitmap>(markerOptions, icon));
navigationLocationManager.setCallback(new NavigationLocationManager.OnNewLocation() {
@Override
public void onNewLocation(Location location) {
marker.setPosition(new LatLng(location.lat,location.lon));
}
@Override
public void onNotInCar() {
marker.setPosition(new LatLng(0,0));
}
});
}
private void setupDeelgebieden() {
Set<String> enabled = JappPreferences.getAreasEnabled();
for(String area : enabled) {
if(!areas.containsKey(area)) {
setupDeelgebied(Deelgebied.parse(area));
}
}
}
public void setupDeelgebied(Deelgebied deelgebied) {
if(!deelgebied.getCoordinates().isEmpty()) {
PolygonOptions options = new PolygonOptions().addAll(deelgebied.getCoordinates());
if(JappPreferences.getAreasColorEnabled()) {
int alphaPercent = JappPreferences.getAreasColorAlpha();
float alpha = ((float)(100 - alphaPercent))/100 * 255;
options.fillColor(deelgebied.alphaled(Math.round(alpha)));
} else {
options.fillColor(Color.TRANSPARENT);
}
options.strokeColor(deelgebied.getColor());
if(JappPreferences.getAreasEdgesEnabled()) {
options.strokeWidth(JappPreferences.getAreasEdgesWidth());
} else {
options.strokeWidth(0);
}
options.visible(true);
areas.put(deelgebied.getName(), jotiMap.addPolygon(options));
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
IPolygon polygon;
switch (key){
case JappPreferences.USE_OSM:
break;
case JappPreferences.AREAS:
if(jotiMap == null) break;
Set<String> enabled = JappPreferences.getAreasEnabled();
for(String area : enabled) {
if(!areas.containsKey(area)) {
setupDeelgebied(Deelgebied.parse(area));
}
}
List<String> toBeRemoved = new ArrayList<>();
for(String area : areas.keySet()) {
if(!enabled.contains(area)) {
IPolygon poly = areas.get(area);
poly.remove();
toBeRemoved.add(area);
}
}
for(String area : toBeRemoved) {
areas.remove(area);
}
break;
case JappPreferences.AREAS_EDGES:
boolean edges = JappPreferences.getAreasEdgesEnabled();
for(HashMap.Entry<String, IPolygon> pair : areas.entrySet()){
polygon = pair.getValue();
if(edges) {
polygon.setStrokeWidth(JappPreferences.getAreasEdgesWidth());
} else {
polygon.setStrokeWidth(0);
}
}
break;
case JappPreferences.AREAS_EDGES_WIDTH:
boolean edgesEnabled = JappPreferences.getAreasEdgesEnabled();
for(HashMap.Entry<String, IPolygon> pair : areas.entrySet()){
polygon = pair.getValue();
if(edgesEnabled) {
polygon.setStrokeWidth(JappPreferences.getAreasEdgesWidth());
}
}
break;
case JappPreferences.AREAS_COLOR:
boolean color = JappPreferences.getAreasColorEnabled();
for(HashMap.Entry<String, IPolygon> pair : areas.entrySet()){
polygon = pair.getValue();
if(color) {
int alphaPercent = JappPreferences.getAreasColorAlpha();
float alpha = ((float)(100 - alphaPercent))/100 * 255;
polygon.setFillColor(Deelgebied.parse(pair.getKey()).alphaled(Math.round(alpha)));
} else {
polygon.setFillColor(Color.TRANSPARENT);
}
}
break;
case JappPreferences.AREAS_COLOR_ALPHA:
boolean areasColorEnabled = JappPreferences.getAreasColorEnabled();
for(HashMap.Entry<String, IPolygon> pair : areas.entrySet()){
polygon = pair.getValue();
if(areasColorEnabled) {
int alphaPercent = JappPreferences.getAreasColorAlpha();
float alpha = ((float)(100 - alphaPercent))/100 * 255;
polygon.setFillColor(Deelgebied.parse(pair.getKey()).alphaled(Math.round(alpha)));
}
}
break;
}
}
public FloatingActionButton setupSpotButton(View v) {
FloatingActionButton spotButton = (FloatingActionButton)v.findViewById(R.id.fab_spot);
spotButton.setOnClickListener(new View.OnClickListener() {
SightingSession session;
@Override
public void onClick(View view) {
/*--- Hide the menu ---*/
View v = getView();
FloatingActionMenu menu = (FloatingActionMenu)v.findViewById(R.id.fab_menu);
menu.hideMenu(true);
/*--- Build a SightingSession and start it ---*/
session = new SightingSession.Builder()
.setType(SightingSession.SIGHT_SPOT)
.setGoogleMap(jotiMap)
.setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container))
.setDialogContext(JappMapFragment.this.getActivity())
.setOnSightingCompletedCallback(new SightingSession.OnSightingCompletedCallback() {
@Override
public void onSightingCompleted(LatLng chosen, Deelgebied deelgebied, String optionalInfo) {
/*--- Show the menu ---*/
FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu);
menu.showMenu(true);
if(chosen != null)
{
/*--- Construct a JSON string with the data ---*/
VosPostBody builder = VosPostBody.getDefault();
builder.setIcon(SightingIcon.SPOT);
builder.setLatLng(chosen);
builder.setTeam(deelgebied.getName().substring(0, 1));
builder.setInfo(optionalInfo);
VosApi api = Japp.getApi(VosApi.class);
api.post(builder).enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
switch (response.code()) {
case 200:
Snackbar.make(snackbarView, "Succesvol verzonden", Snackbar.LENGTH_LONG).show();
break;
case 404:
Snackbar.make(snackbarView, "Verkeerde gegevens", Snackbar.LENGTH_LONG).show();
break;
default:
Snackbar.make(snackbarView, "Probleem bij verzenden: " + response.code(), Snackbar.LENGTH_LONG).show();
break;
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
Snackbar.make(snackbarView, "Probleem bij verzenden: " + t.toString() , Snackbar.LENGTH_LONG).show();
}
});
/**
* TODO: send details?
* Log the spot in firebase.
* */
Japp.getAnalytics().logEvent("EVENT_SPOT", new Bundle());
}
session = null;
}
})
.create();
session.start();
}
});
return spotButton;
}
public FloatingActionButton setupFollowButton(View v) {
FloatingActionButton followButton = (FloatingActionButton) v.findViewById(R.id.fab_follow);
followButton.setOnClickListener(new View.OnClickListener() {
MovementManager.FollowSession session;
@Override
public void onClick(View view) {
View v = getView();
FloatingActionButton followButton = (FloatingActionButton) v.findViewById(R.id.fab_follow);
/*--- Hide the menu ---*/
FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu);
/**
* TODO: use color to identify follow state?
* */
if (session != null) {
// followButton.setColorNormal(Color.parseColor("#DA4336"));
followButton.setLabelText("Volg mij");
session.end();
session = null;
} else {
menu.close(true);
//followButton.setColorNormal(Color.parseColor("#5cd65c"));
followButton.setLabelText("Stop volgen");
session = movementManager.newSession(jotiMap.getPreviousCameraPosition(), JappPreferences.getFollowZoom(), JappPreferences.getFollowAngleOfAttack());
}
}
});
return followButton;
}
private FloatingActionButton setupPinButton(View v) {
FloatingActionButton pinButton = (FloatingActionButton)v.findViewById(R.id.fab_mark);
pinButton.setOnClickListener(new View.OnClickListener() {
PinningSession session;
@Override
public void onClick(View view) {
View v = getView();
FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu);
if(session != null) {
/*--- Show the menu ---*/
menu.showMenu(true);
session.end();
session = null;
} else {
/*--- Hide the menu ---*/
menu.hideMenu(true);
session = new PinningSession.Builder()
.setJotiMap(jotiMap)
.setCallback(new PinningSession.OnPinningCompletedCallback() {
@Override
public void onPinningCompleted(Pin pin) {
if(pin != null) {
pinningManager.add(pin);
}
FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu);
menu.showMenu(true);
session.end();
session = null;
}
})
.setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container))
.setDialogContext(JappMapFragment.this.getActivity())
.create();
session.start();
}
}
});
return pinButton;
}
private FloatingActionButton setupNavigationButton(View v) {
FloatingActionButton navigationButton = (FloatingActionButton)v.findViewById(R.id.fab_nav);
navigationButton.setOnClickListener(new View.OnClickListener() {
NavigationSession session;
@Override
public void onClick(View view) {
View v = getView();
FloatingActionMenu menu = (FloatingActionMenu) v.findViewById(R.id.fab_menu);
if(session != null) {
/*--- Show the menu ---*/
menu.showMenu(true);
session.end();
session = null;
} else {
/*--- Hide the menu ---*/
menu.hideMenu(true);
session = new NavigationSession.Builder()
.setJotiMap(jotiMap)
.setCallback(new NavigationSession.OnNavigationCompletedCallback() {
@Override
public void onNavigationCompleted(final LatLng navigateTo, boolean toNavigationPhone) {
FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu);
menu.showMenu(true);
session.end();
session = null;
if (navigateTo != null) {
if (!toNavigationPhone) {
try{
switch(JappPreferences.navigationApp()){
case GoogleMaps:
String uristr = "google.navigation:q=" + Double.toString(navigateTo.latitude) + "," + Double.toString(navigateTo.longitude);
Uri gmmIntentUri = Uri.parse(uristr);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
break;
case Waze:
String uri = "waze://?ll="+Double.toString(navigateTo.latitude) +","+Double.toString(navigateTo.longitude) +"&navigate=yes";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
break;
}
} catch (ActivityNotFoundException e){
System.out.println(e.toString());
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
Snackbar.make(snackbarView, "De App: " + JappPreferences.navigationApp().toString() +" is niet geinstaleerd.", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string
}
}else{
int id = JappPreferences.getAccountId();
if (id >= 0) {
final AutoApi autoApi = Japp.getApi(AutoApi.class);
autoApi.getInfoById(JappPreferences.getAccountKey(), id).enqueue(new Callback<AutoInzittendeInfo>() {
@Override
public void onResponse(Call<AutoInzittendeInfo> call, Response<AutoInzittendeInfo> response) {
if (response.code() == 200) {
AutoInzittendeInfo autoInfo = response.body();
if (autoInfo != null) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(NavigationLocationManager.FDB_NAME + "/" + autoInfo.autoEigenaar);
ref.setValue(new Location(navigateTo, JappPreferences.getAccountUsername()));
}
}
if (response.code() == 404){
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
Snackbar.make(snackbarView, "Fout: plaats jezelf eerst in een auto via telegram.", Snackbar.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<AutoInzittendeInfo> call, Throwable t) {
}
});
}
}
}
}
})
.setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container))
.setDialogContext(JappMapFragment.this.getActivity())
.create();
session.start();
}
}
});
return navigationButton;
}
private FloatingActionButton setupHuntButton(View v){
FloatingActionButton huntButton = (FloatingActionButton)v.findViewById(R.id.fab_hunt);
huntButton.setOnClickListener(new View.OnClickListener() {
SightingSession session;
@Override
public void onClick(View view) {
/*--- Hide the menu ---*/
View v = getView();
FloatingActionMenu menu = (FloatingActionMenu)v.findViewById(R.id.fab_menu);
menu.hideMenu(true);
/*--- Build a SightingSession and start it ---*/
session = new SightingSession.Builder()
.setType(SightingSession.SIGHT_HUNT)
.setGoogleMap(jotiMap)
.setTargetView(JappMapFragment.this.getActivity().findViewById(R.id.container))
.setDialogContext(JappMapFragment.this.getActivity())
.setOnSightingCompletedCallback(new SightingSession.OnSightingCompletedCallback() {
@Override
public void onSightingCompleted(LatLng chosen, Deelgebied deelgebied, String optionalInfo) {
/*--- Show the menu ---*/
FloatingActionMenu menu = (FloatingActionMenu)getView().findViewById(R.id.fab_menu);
menu.showMenu(true);
if(chosen != null)
{
/*--- Construct a JSON string with the data ---*/
VosPostBody builder = VosPostBody.getDefault();
builder.setIcon(SightingIcon.HUNT);
builder.setLatLng(chosen);
builder.setTeam(deelgebied.getName().substring(0, 1));
builder.setInfo(optionalInfo);
VosApi api = Japp.getApi(VosApi.class);
api.post(builder).enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
switch (response.code()) {
case 200:
Snackbar.make(snackbarView, "Succesvol verzonden", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string
break;
case 404:
Snackbar.make(snackbarView, "Verkeerde gegevens", Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string
break;
default:
Snackbar.make(snackbarView, "Probleem bij verzenden: " + response.code(), Snackbar.LENGTH_LONG).show(); //// TODO: 08/08/17 magic string
break;
}
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
View snackbarView = JappMapFragment.this.getActivity().findViewById(R.id.container);
Snackbar.make(snackbarView, "Probleem bij verzenden: " + t.toString() , Snackbar.LENGTH_LONG).show();//// TODO: 08/08/17 magic string
}
});
/**
* TODO: send details?
* Log the hunt in firebase.
* */
Japp.getAnalytics().logEvent("EVENT_HUNT", new Bundle()); //// TODO: 08/08/17 magic string
}
}
})
.create();
session.start();
}
});
return huntButton;
}
}
| tried to fix #112
| app/src/main/java/nl/rsdt/japp/application/fragments/JappMapFragment.java | tried to fix #112 | <ide><path>pp/src/main/java/nl/rsdt/japp/application/fragments/JappMapFragment.java
<ide> setupDeelgebied(Deelgebied.parse(area));
<ide> }
<ide> }
<add> if(jotiMap instanceof OsmJotiMap) {
<add> ((OsmJotiMap) jotiMap).getOSMMap().invalidate();
<add> }
<ide> }
<ide>
<ide> public void setupDeelgebied(Deelgebied deelgebied) {
<ide>
<ide> for(String area : toBeRemoved) {
<ide> areas.remove(area);
<add> }
<add> if(jotiMap instanceof OsmJotiMap) {
<add> ((OsmJotiMap) jotiMap).getOSMMap().invalidate();
<ide> }
<ide> break;
<ide> case JappPreferences.AREAS_EDGES: |
|
JavaScript | mit | c0729982b57d5ac90ab09c8f39d4b46851fa477d | 0 | GAMELASTER/facebook-chat-api,Schmavery/facebook-chat-api,ravkr/facebook-chat-api | "use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function(defaultFuncs, api, ctx) {
return function changeThreadColor(color, threadID, callback) {
if(!callback) {
callback = function() {};
}
var form = {
'color_choice' : color,
'thread_or_other_fbid' : threadID
};
defaultFuncs
.post("https://www.messenger.com/messaging/save_thread_color/?source=thread_settings&dpr=1", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs))
.then(function(resData) {
if (resData.error === 1357031) {
throw {error: "Trying to change colors of a chat that doesn't exist. Have at least one message in the thread before trying to change the colors."};
}
if (resData.error) {
throw resData;
}
return callback();
})
.catch(function(err) {
log.error("Error in changeThreadColor", err);
return callback(err);
});
};
};
| src/changeThreadColor.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function(defaultFuncs, api, ctx) {
return function changeThreadColor(color, threadID, callback) {
var form = {
'color_choice' : color,
'thread_or_other_fbid' : threadID
};
defaultFuncs
.post("https://www.messenger.com/messaging/save_thread_color/?source=thread_settings&dpr=1", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs))
.then(function(resData) {
if (resData.error === 1357031) {
throw {error: "Trying to change colors of a chat that doesn't exist. Have at least one message in the thread before trying to change the colors."};
}
if (resData.error) {
throw resData;
}
return callback();
})
.catch(function(err) {
log.error("Error in changeThreadColor", err);
return callback(err);
});
};
};
| Fix thread color parameter as optional
| src/changeThreadColor.js | Fix thread color parameter as optional | <ide><path>rc/changeThreadColor.js
<ide>
<ide> module.exports = function(defaultFuncs, api, ctx) {
<ide> return function changeThreadColor(color, threadID, callback) {
<add> if(!callback) {
<add> callback = function() {};
<add> }
<ide> var form = {
<ide> 'color_choice' : color,
<ide> 'thread_or_other_fbid' : threadID |
|
Java | bsd-3-clause | 340d0c9f8c7465ed64409de8699aae06d1ac96e5 | 0 | jenkinsci/jaxen | /*
* $Header$
* $Revision: 719 $
* $Date: 2005-05-03 05:27:12 -0700 (Tue, 03 May 2005) $
*
* ====================================================================
*
* Copyright (C) 2000-2002 bob mcwhirter & James Strachan.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions, and the disclaimer that follows
* these conditions in the documentation and/or other materials
* provided with the distribution.
*
* 3. The name "Jaxen" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 4. Products derived from this software may not be called "Jaxen", nor
* may "Jaxen" appear in their name, without prior written permission
* from the Jaxen Project Management ([email protected]).
*
* In addition, we request (but do not require) that you include in the
* end-user documentation provided with the redistribution and/or in the
* software itself an acknowledgement equivalent to the following:
* "This product includes software developed by the
* Jaxen Project (http://www.jaxen.org/)."
* Alternatively, the acknowledgment may be graphical using the logos
* available at http://www.jaxen.org/
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE Jaxen AUTHORS OR THE PROJECT
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <[email protected]> and
* James Strachan <[email protected]>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id: XPathReaderTest.java 719 2005-05-03 12:27:12Z elharo $
*/
package org.jaxen.saxpath.base;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import junit.framework.TestCase;
import org.jaxen.JaxenException;
import org.jaxen.XPath;
import org.jaxen.dom.DOMXPath;
import org.jaxen.saxpath.Axis;
import org.jaxen.saxpath.Operator;
import org.jaxen.saxpath.SAXPathException;
import org.jaxen.saxpath.XPathSyntaxException;
import org.jaxen.saxpath.conformance.ConformanceXPathHandler;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XPathReaderTest extends TestCase
{
private ConformanceXPathHandler expected;
private ConformanceXPathHandler actual;
private Document doc;
private XPathReader reader;
private String text;
private String[] paths = {
"/foo/bar[@a='1' and @b='2']",
"/foo/bar[@a='1' and @b!='2']",
"$varname[@a='1']",
"//attribute::*[.!='crunchy']",
"'//*[contains(string(text()),\"yada yada\")]'",
};
private String[][] bogusPaths = {
new String[]{"chyld::foo", "Expected valid axis name instead of [chyld]"},
new String[]{"foo/tacos()", "Expected node-type"},
new String[]{"foo/tacos()", "Expected node-type"},
new String[]{"*:foo", "Unexpected ':'"},
new String[]{"/foo/bar[baz", "Expected: ]"},
new String[]{"/cracker/cheese[(mold > 1) and (sense/taste", "Expected: )"},
new String[]{"//", "Location path cannot end with //"},
new String[]{"foo/$variable/foo", "Expected one of '.', '..', '@', '*', <QName>"}
};
public XPathReaderTest( String name )
{
super( name );
}
public void setUp() throws ParserConfigurationException, SAXException, IOException
{
setReader( new XPathReader() );
setText( null );
this.actual = new ConformanceXPathHandler();
this.expected = new ConformanceXPathHandler();
getReader().setXPathHandler( actual() );
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse( "xml/basic.xml" );
}
public void tearDown()
{
setReader( null );
setText( null );
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
public void testPaths() throws SAXPathException
{
for( int i = 0; i < paths.length; ++i )
{
reader.parse( paths[i] );
}
}
public void testBogusPaths() throws SAXPathException
{
for( int i = 0; i < bogusPaths.length; ++i )
{
final String[] bogusPath = bogusPaths[i];
try
{
reader.parse( bogusPath[0] );
fail( "Should have thrown XPathSyntaxException for " + bogusPath[0]);
}
catch( XPathSyntaxException e )
{
assertEquals( bogusPath[1], e.getMessage() );
}
}
}
public void testChildrenOfNumber() throws SAXPathException
{
try
{
reader.parse( "1/child::test" );
fail( "Should have thrown XPathSyntaxException for 1/child::test");
}
catch( XPathSyntaxException e )
{
assertEquals( "Node-set expected", e.getMessage() );
}
}
public void testChildIsNumber() throws SAXPathException
{
try
{
reader.parse( "jane/3" );
fail( "Should have thrown XPathSyntaxException for jane/3");
}
catch( XPathSyntaxException e )
{
assertEquals( "Expected one of '.', '..', '@', '*', <QName>", e.getMessage() );
}
}
public void testNumberOrNumber()
{
try
{
XPath xpath = new DOMXPath( "4 | 5" );
xpath.selectNodes( doc );
fail( "Should have thrown XPathSyntaxException for 4 | 5");
}
catch( JaxenException e )
{
assertEquals( "Unions are only allowed over node-sets", e.getMessage() );
}
}
public void testStringOrNumber()
{
try
{
XPath xpath = new DOMXPath( "\"test\" | 5" );
xpath.selectNodes( doc );
fail( "Should have thrown XPathSyntaxException for \"test\" | 5");
}
catch( JaxenException e )
{
assertEquals( "Unions are only allowed over node-sets", e.getMessage() );
}
}
public void testStringOrString()
{
try
{
XPath xpath = new DOMXPath( "\"test\" | \"festival\"" );
xpath.selectNodes( doc );
fail( "Should have thrown XPathSyntaxException for \"test\" | 5");
}
catch( JaxenException e )
{
assertEquals( "Unions are only allowed over node-sets", e.getMessage() );
}
}
public void testUnionofNodesAndNonNodes()
{
try
{
XPath xpath = new DOMXPath( "count(//*) | //* " );
xpath.selectNodes( doc );
fail( "Should have thrown XPathSyntaxException for \"count(//*) | //* ");
}
catch( JaxenException e )
{
assertEquals( "Unions are only allowed over node-sets", e.getMessage() );
}
}
public void testValidAxis() throws SAXPathException
{
reader.parse( "child::foo" );
}
public void testInvalidAxis() throws SAXPathException
{
try
{
reader.parse( "chyld::foo" );
fail( "Should have thrown XPathSyntaxException" );
}
catch( XPathSyntaxException ex )
{
assertNotNull(ex.getMessage());
}
}
public void testSimpleNameStep() throws SAXPathException
{
setText( "foo" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startNameStep( Axis.CHILD,
"",
"foo" );
expected().endNameStep();
compare();
}
public void testNameStepWithAxisAndPrefix() throws SAXPathException
{
setText( "parent::foo:bar" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startNameStep( Axis.PARENT,
"foo",
"bar" );
expected().endNameStep();
compare();
}
public void testNodeStepWithAxis() throws SAXPathException
{
setText( "parent::node()" );
getReader().setUpParse( getText() );
getReader().step();
expected().startAllNodeStep( Axis.PARENT );
expected().endAllNodeStep();
compare();
}
public void testProcessingInstructionStepWithName() throws SAXPathException
{
setText( "parent::processing-instruction('cheese')" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startProcessingInstructionNodeStep( Axis.PARENT,
"cheese" );
expected().endProcessingInstructionNodeStep();
compare();
}
public void testProcessingInstructionStepNoName() throws SAXPathException
{
setText( "parent::processing-instruction()" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startProcessingInstructionNodeStep( Axis.PARENT,
"" );
expected().endProcessingInstructionNodeStep();
compare();
}
public void testAllNodeStep() throws SAXPathException
{
setText( "parent::node()" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startAllNodeStep( Axis.PARENT );
expected().endAllNodeStep();
compare();
}
public void testTextNodeStep() throws SAXPathException
{
setText( "parent::text()" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startTextNodeStep( Axis.PARENT );
expected().endTextNodeStep();
compare();
}
public void testCommentNodeStep() throws SAXPathException
{
setText( "parent::comment()" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startCommentNodeStep( Axis.PARENT );
expected().endCommentNodeStep();
compare();
}
public void testLocationPathStartsWithVariable() throws SAXPathException
{
setText( "$variable/foo" );
getReader().setUpParse( getText() );
getReader().step();
}
public void testRelativeLocationPath() throws SAXPathException
{
setText( "foo/bar/baz" );
getReader().setUpParse( getText() );
getReader().locationPath( false );
expected().startRelativeLocationPath();
expected().startNameStep( Axis.CHILD,
"",
"foo" );
expected().endNameStep();
expected().startNameStep( Axis.CHILD,
"",
"bar" );
expected().endNameStep();
expected().startNameStep( Axis.CHILD,
"",
"baz" );
expected().endNameStep();
expected().endRelativeLocationPath();
compare();
}
public void testAbsoluteLocationPath() throws SAXPathException
{
setText( "/foo/bar/baz" );
getReader().setUpParse( getText() );
getReader().locationPath( true );
expected().startAbsoluteLocationPath();
expected().startNameStep( Axis.CHILD,
"",
"foo" );
expected().endNameStep();
expected().startNameStep( Axis.CHILD,
"",
"bar" );
expected().endNameStep();
expected().startNameStep( Axis.CHILD,
"",
"baz" );
expected().endNameStep();
expected().endAbsoluteLocationPath();
compare();
}
public void testNumberPredicate() throws SAXPathException
{
setText( "[1]" );
getReader().setUpParse( getText() );
getReader().predicate();
expected().startPredicate();
expected().startOrExpr();
expected().startAndExpr();
expected().startEqualityExpr();
expected().startEqualityExpr();
expected().startRelationalExpr();
expected().startRelationalExpr();
expected().startAdditiveExpr();
expected().startAdditiveExpr();
expected().startMultiplicativeExpr();
expected().startMultiplicativeExpr();
expected().startUnaryExpr();
expected().startUnionExpr();
expected().startPathExpr();
expected().startFilterExpr();
expected().number( 1 );
expected().endFilterExpr();
expected().endPathExpr();
expected().endUnionExpr( false );
expected().endUnaryExpr( Operator.NO_OP );
expected().endMultiplicativeExpr( Operator.NO_OP );
expected().endMultiplicativeExpr( Operator.NO_OP );
expected().endAdditiveExpr( Operator.NO_OP );
expected().endAdditiveExpr( Operator.NO_OP );
expected().endRelationalExpr( Operator.NO_OP );
expected().endRelationalExpr( Operator.NO_OP );
expected().endEqualityExpr( Operator.NO_OP );
expected().endEqualityExpr( Operator.NO_OP );
expected().endAndExpr( false );
expected().endOrExpr( false );
expected().endPredicate();
compare();
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
private void setText( String text )
{
this.text = text;
}
private String getText()
{
return this.text;
}
private void setReader( XPathReader reader )
{
this.reader = reader;
}
private XPathReader getReader()
{
return this.reader;
}
private void compare()
{
assertEquals( expected(),
actual() );
}
private ConformanceXPathHandler expected()
{
return this.expected;
}
private ConformanceXPathHandler actual()
{
return this.actual;
}
}
| src/java/test/org/jaxen/saxpath/base/XPathReaderTest.java | /*
* $Header$
* $Revision: 718 $
* $Date: 2005-05-03 05:25:17 -0700 (Tue, 03 May 2005) $
*
* ====================================================================
*
* Copyright (C) 2000-2002 bob mcwhirter & James Strachan.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions, and the disclaimer that follows
* these conditions in the documentation and/or other materials
* provided with the distribution.
*
* 3. The name "Jaxen" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 4. Products derived from this software may not be called "Jaxen", nor
* may "Jaxen" appear in their name, without prior written permission
* from the Jaxen Project Management ([email protected]).
*
* In addition, we request (but do not require) that you include in the
* end-user documentation provided with the redistribution and/or in the
* software itself an acknowledgement equivalent to the following:
* "This product includes software developed by the
* Jaxen Project (http://www.jaxen.org/)."
* Alternatively, the acknowledgment may be graphical using the logos
* available at http://www.jaxen.org/
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE Jaxen AUTHORS OR THE PROJECT
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <[email protected]> and
* James Strachan <[email protected]>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id: XPathReaderTest.java 718 2005-05-03 12:25:17Z elharo $
*/
package org.jaxen.saxpath.base;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import junit.framework.TestCase;
import org.jaxen.JaxenException;
import org.jaxen.XPath;
import org.jaxen.dom.DOMXPath;
import org.jaxen.saxpath.Axis;
import org.jaxen.saxpath.Operator;
import org.jaxen.saxpath.SAXPathException;
import org.jaxen.saxpath.XPathSyntaxException;
import org.jaxen.saxpath.conformance.ConformanceXPathHandler;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XPathReaderTest extends TestCase
{
private ConformanceXPathHandler expected;
private ConformanceXPathHandler actual;
private Document doc;
private XPathReader reader;
private String text;
private String[] paths = {
"/foo/bar[@a='1' and @b='2']",
"/foo/bar[@a='1' and @b!='2']",
"$varname[@a='1']",
"//attribute::*[.!='crunchy']",
"'//*[contains(string(text()),\"yada yada\")]'",
};
private String[][] bogusPaths = {
new String[]{"chyld::foo", "Expected valid axis name instead of [chyld]"},
new String[]{"foo/tacos()", "Expected node-type"},
new String[]{"foo/tacos()", "Expected node-type"},
new String[]{"*:foo", "Unexpected ':'"},
new String[]{"/foo/bar[baz", "Expected: ]"},
new String[]{"/cracker/cheese[(mold > 1) and (sense/taste", "Expected: )"},
new String[]{"//", "Location path cannot end with //"}
};
public XPathReaderTest( String name )
{
super( name );
}
public void setUp() throws ParserConfigurationException, SAXException, IOException
{
setReader( new XPathReader() );
setText( null );
this.actual = new ConformanceXPathHandler();
this.expected = new ConformanceXPathHandler();
getReader().setXPathHandler( actual() );
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse( "xml/basic.xml" );
}
public void tearDown()
{
setReader( null );
setText( null );
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
public void testPaths() throws SAXPathException
{
for( int i = 0; i < paths.length; ++i )
{
reader.parse( paths[i] );
}
}
public void testBogusPaths() throws SAXPathException
{
for( int i = 0; i < bogusPaths.length; ++i )
{
final String[] bogusPath = bogusPaths[i];
try
{
reader.parse( bogusPath[0] );
fail( "Should have thrown XPathSyntaxException for " + bogusPath[0]);
}
catch( XPathSyntaxException e )
{
assertEquals( bogusPath[1], e.getMessage() );
}
}
}
public void testChildrenOfNumber() throws SAXPathException
{
try
{
reader.parse( "1/child::test" );
fail( "Should have thrown XPathSyntaxException for 1/child::test");
}
catch( XPathSyntaxException e )
{
assertEquals( "Node-set expected", e.getMessage() );
}
}
public void testChildIsNumber() throws SAXPathException
{
try
{
reader.parse( "jane/3" );
fail( "Should have thrown XPathSyntaxException for jane/3");
}
catch( XPathSyntaxException e )
{
assertEquals( "Expected one of '.', '..', '@', '*', <QName>", e.getMessage() );
}
}
public void testNumberOrNumber()
{
try
{
XPath xpath = new DOMXPath( "4 | 5" );
xpath.selectNodes( doc );
fail( "Should have thrown XPathSyntaxException for 4 | 5");
}
catch( JaxenException e )
{
assertEquals( "Unions are only allowed over node-sets", e.getMessage() );
}
}
public void testStringOrNumber()
{
try
{
XPath xpath = new DOMXPath( "\"test\" | 5" );
xpath.selectNodes( doc );
fail( "Should have thrown XPathSyntaxException for \"test\" | 5");
}
catch( JaxenException e )
{
assertEquals( "Unions are only allowed over node-sets", e.getMessage() );
}
}
public void testStringOrString()
{
try
{
XPath xpath = new DOMXPath( "\"test\" | \"festival\"" );
xpath.selectNodes( doc );
fail( "Should have thrown XPathSyntaxException for \"test\" | 5");
}
catch( JaxenException e )
{
assertEquals( "Unions are only allowed over node-sets", e.getMessage() );
}
}
public void testUnionofNodesAndNonNodes()
{
try
{
XPath xpath = new DOMXPath( "count(//*) | //* " );
xpath.selectNodes( doc );
fail( "Should have thrown XPathSyntaxException for \"count(//*) | //* ");
}
catch( JaxenException e )
{
assertEquals( "Unions are only allowed over node-sets", e.getMessage() );
}
}
public void testValidAxis() throws SAXPathException
{
reader.parse( "child::foo" );
}
public void testInvalidAxis() throws SAXPathException
{
try
{
reader.parse( "chyld::foo" );
fail( "Should have thrown XPathSyntaxException" );
}
catch( XPathSyntaxException ex )
{
assertNotNull(ex.getMessage());
}
}
public void testSimpleNameStep() throws SAXPathException
{
setText( "foo" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startNameStep( Axis.CHILD,
"",
"foo" );
expected().endNameStep();
compare();
}
public void testNameStepWithAxisAndPrefix() throws SAXPathException
{
setText( "parent::foo:bar" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startNameStep( Axis.PARENT,
"foo",
"bar" );
expected().endNameStep();
compare();
}
public void testNodeStepWithAxis() throws SAXPathException
{
setText( "parent::node()" );
getReader().setUpParse( getText() );
getReader().step();
expected().startAllNodeStep( Axis.PARENT );
expected().endAllNodeStep();
compare();
}
public void testProcessingInstructionStepWithName() throws SAXPathException
{
setText( "parent::processing-instruction('cheese')" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startProcessingInstructionNodeStep( Axis.PARENT,
"cheese" );
expected().endProcessingInstructionNodeStep();
compare();
}
public void testProcessingInstructionStepNoName() throws SAXPathException
{
setText( "parent::processing-instruction()" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startProcessingInstructionNodeStep( Axis.PARENT,
"" );
expected().endProcessingInstructionNodeStep();
compare();
}
public void testAllNodeStep() throws SAXPathException
{
setText( "parent::node()" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startAllNodeStep( Axis.PARENT );
expected().endAllNodeStep();
compare();
}
public void testTextNodeStep() throws SAXPathException
{
setText( "parent::text()" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startTextNodeStep( Axis.PARENT );
expected().endTextNodeStep();
compare();
}
public void testCommentNodeStep() throws SAXPathException
{
setText( "parent::comment()" );
getReader().setUpParse( getText() );
getReader().step( );
expected().startCommentNodeStep( Axis.PARENT );
expected().endCommentNodeStep();
compare();
}
public void testLocationPathStartsWithVariable() throws SAXPathException
{
setText( "$variable/foo" );
getReader().setUpParse( getText() );
getReader().step();
}
public void testRelativeLocationPath() throws SAXPathException
{
setText( "foo/bar/baz" );
getReader().setUpParse( getText() );
getReader().locationPath( false );
expected().startRelativeLocationPath();
expected().startNameStep( Axis.CHILD,
"",
"foo" );
expected().endNameStep();
expected().startNameStep( Axis.CHILD,
"",
"bar" );
expected().endNameStep();
expected().startNameStep( Axis.CHILD,
"",
"baz" );
expected().endNameStep();
expected().endRelativeLocationPath();
compare();
}
public void testAbsoluteLocationPath() throws SAXPathException
{
setText( "/foo/bar/baz" );
getReader().setUpParse( getText() );
getReader().locationPath( true );
expected().startAbsoluteLocationPath();
expected().startNameStep( Axis.CHILD,
"",
"foo" );
expected().endNameStep();
expected().startNameStep( Axis.CHILD,
"",
"bar" );
expected().endNameStep();
expected().startNameStep( Axis.CHILD,
"",
"baz" );
expected().endNameStep();
expected().endAbsoluteLocationPath();
compare();
}
public void testNumberPredicate() throws SAXPathException
{
setText( "[1]" );
getReader().setUpParse( getText() );
getReader().predicate();
expected().startPredicate();
expected().startOrExpr();
expected().startAndExpr();
expected().startEqualityExpr();
expected().startEqualityExpr();
expected().startRelationalExpr();
expected().startRelationalExpr();
expected().startAdditiveExpr();
expected().startAdditiveExpr();
expected().startMultiplicativeExpr();
expected().startMultiplicativeExpr();
expected().startUnaryExpr();
expected().startUnionExpr();
expected().startPathExpr();
expected().startFilterExpr();
expected().number( 1 );
expected().endFilterExpr();
expected().endPathExpr();
expected().endUnionExpr( false );
expected().endUnaryExpr( Operator.NO_OP );
expected().endMultiplicativeExpr( Operator.NO_OP );
expected().endMultiplicativeExpr( Operator.NO_OP );
expected().endAdditiveExpr( Operator.NO_OP );
expected().endAdditiveExpr( Operator.NO_OP );
expected().endRelationalExpr( Operator.NO_OP );
expected().endRelationalExpr( Operator.NO_OP );
expected().endEqualityExpr( Operator.NO_OP );
expected().endEqualityExpr( Operator.NO_OP );
expected().endAndExpr( false );
expected().endOrExpr( false );
expected().endPredicate();
compare();
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
private void setText( String text )
{
this.text = text;
}
private String getText()
{
return this.text;
}
private void setReader( XPathReader reader )
{
this.reader = reader;
}
private XPathReader getReader()
{
return this.reader;
}
private void compare()
{
assertEquals( expected(),
actual() );
}
private ConformanceXPathHandler expected()
{
return this.expected;
}
private ConformanceXPathHandler actual()
{
return this.actual;
}
}
| Adding test that foo/$variable/foo is an illegal path;
variables cannot be relative location steps.
| src/java/test/org/jaxen/saxpath/base/XPathReaderTest.java | Adding test that foo/$variable/foo is an illegal path; variables cannot be relative location steps. | <ide><path>rc/java/test/org/jaxen/saxpath/base/XPathReaderTest.java
<ide> /*
<ide> * $Header$
<del> * $Revision: 718 $
<del> * $Date: 2005-05-03 05:25:17 -0700 (Tue, 03 May 2005) $
<add> * $Revision: 719 $
<add> * $Date: 2005-05-03 05:27:12 -0700 (Tue, 03 May 2005) $
<ide> *
<ide> * ====================================================================
<ide> *
<ide> * James Strachan <[email protected]>. For more information on the
<ide> * Jaxen Project, please see <http://www.jaxen.org/>.
<ide> *
<del> * $Id: XPathReaderTest.java 718 2005-05-03 12:25:17Z elharo $
<add> * $Id: XPathReaderTest.java 719 2005-05-03 12:27:12Z elharo $
<ide> */
<ide>
<ide>
<ide> new String[]{"*:foo", "Unexpected ':'"},
<ide> new String[]{"/foo/bar[baz", "Expected: ]"},
<ide> new String[]{"/cracker/cheese[(mold > 1) and (sense/taste", "Expected: )"},
<del> new String[]{"//", "Location path cannot end with //"}
<add> new String[]{"//", "Location path cannot end with //"},
<add> new String[]{"foo/$variable/foo", "Expected one of '.', '..', '@', '*', <QName>"}
<ide> };
<ide>
<ide> public XPathReaderTest( String name ) |
|
Java | apache-2.0 | ca991fa1c101d7a98c5c654fde632352848633c0 | 0 | nssales/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,jerome79/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.view.calc;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.time.Instant;
import org.testng.annotations.Test;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.engine.marketdata.InMemoryLKVMarketDataProvider;
import com.opengamma.engine.marketdata.LiveMarketDataProvider;
import com.opengamma.engine.marketdata.LiveMarketDataSnapshot;
import com.opengamma.engine.marketdata.MarketDataListener;
import com.opengamma.engine.marketdata.MarketDataProvider;
import com.opengamma.engine.marketdata.MarketDataSnapshot;
import com.opengamma.engine.marketdata.availability.MarketDataAvailabilityProvider;
import com.opengamma.engine.marketdata.permission.MarketDataPermissionProvider;
import com.opengamma.engine.marketdata.permission.PermissiveMarketDataPermissionProvider;
import com.opengamma.engine.marketdata.resolver.MarketDataProviderResolver;
import com.opengamma.engine.marketdata.spec.LiveMarketDataSpecification;
import com.opengamma.engine.marketdata.spec.MarketData;
import com.opengamma.engine.marketdata.spec.MarketDataSpecification;
import com.opengamma.engine.test.MockSecuritySource;
import com.opengamma.engine.test.TestViewResultListener;
import com.opengamma.engine.test.ViewProcessorTestEnvironment;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.view.ViewComputationResultModel;
import com.opengamma.engine.view.ViewProcessImpl;
import com.opengamma.engine.view.ViewProcessorImpl;
import com.opengamma.engine.view.ViewTargetResultModel;
import com.opengamma.engine.view.client.ViewClient;
import com.opengamma.engine.view.execution.ArbitraryViewCycleExecutionSequence;
import com.opengamma.engine.view.execution.ExecutionFlags;
import com.opengamma.engine.view.execution.ExecutionOptions;
import com.opengamma.engine.view.execution.ViewCycleExecutionOptions;
import com.opengamma.engine.view.execution.ViewExecutionFlags;
import com.opengamma.engine.view.execution.ViewExecutionOptions;
import com.opengamma.livedata.LiveDataClient;
import com.opengamma.livedata.LiveDataListener;
import com.opengamma.livedata.LiveDataSpecification;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.livedata.msg.LiveDataSubscriptionResponse;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.test.Timeout;
/**
* Tests {@link ViewComputationJob}
*/
public class ViewComputationJobTest {
private static final long TIMEOUT = 5L * Timeout.standardTimeoutMillis();
private static final String SOURCE_1_NAME = "source1";
private static final String SOURCE_2_NAME = "source2";
@Test
public void testInterruptJobBetweenCycles() throws InterruptedException {
// Due to all the dependencies between components for execution to take place, it's easiest to test it in a
// realistic environment. In its default configuration, only live data can trigger a computation cycle (after the
// initial cycle).
ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
env.init();
ViewProcessorImpl vp = env.getViewProcessor();
vp.start();
ViewClient client = vp.createViewClient(ViewProcessorTestEnvironment.TEST_USER);
TestViewResultListener resultListener = new TestViewResultListener();
client.setResultListener(resultListener);
client.attachToViewProcess(env.getViewDefinition().getName(), ExecutionOptions.infinite(MarketData.live()));
// Consume the initial result
resultListener.assertViewDefinitionCompiled(TIMEOUT);
resultListener.assertCycleCompleted(TIMEOUT);
ViewProcessImpl viewProcess = env.getViewProcess(vp, client.getUniqueId());
Thread recalcThread = env.getCurrentComputationThread(viewProcess);
assertThreadReachesState(recalcThread, Thread.State.TIMED_WAITING);
// We're now 'between cycles', waiting for the arrival of live data.
// Interrupting should terminate the job gracefully
ViewComputationJob job = env.getCurrentComputationJob(viewProcess);
job.terminate();
recalcThread.interrupt();
recalcThread.join(TIMEOUT);
assertEquals(Thread.State.TERMINATED, recalcThread.getState());
}
@Test
public void testWaitForMarketData() throws InterruptedException {
final ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
InMemoryLKVMarketDataProvider underlyingProvider = new InMemoryLKVMarketDataProvider();
MarketDataProvider marketDataProvider = new TestLiveMarketDataProvider("source", underlyingProvider);
env.setMarketDataProvider(marketDataProvider);
env.init();
ViewProcessorImpl vp = env.getViewProcessor();
vp.start();
ViewClient client = vp.createViewClient(ViewProcessorTestEnvironment.TEST_USER);
TestViewResultListener resultListener = new TestViewResultListener();
client.setResultListener(resultListener);
ViewCycleExecutionOptions cycleExecutionOptions = new ViewCycleExecutionOptions(Instant.now(), MarketData.live());
EnumSet<ViewExecutionFlags> flags = ExecutionFlags.none().awaitMarketData().get();
ViewExecutionOptions executionOptions = ExecutionOptions.of(ArbitraryViewCycleExecutionSequence.single(cycleExecutionOptions), flags);
client.attachToViewProcess(env.getViewDefinition().getName(), executionOptions);
resultListener.assertViewDefinitionCompiled(TIMEOUT);
ViewProcessImpl viewProcess = env.getViewProcess(vp, client.getUniqueId());
Thread recalcThread = env.getCurrentComputationThread(viewProcess);
assertThreadReachesState(recalcThread, Thread.State.TIMED_WAITING);
underlyingProvider.addValue(ViewProcessorTestEnvironment.getPrimitive1(), 123d);
underlyingProvider.addValue(ViewProcessorTestEnvironment.getPrimitive2(), 456d);
recalcThread.join();
resultListener.assertCycleCompleted(TIMEOUT);
Map<String, Object> resultValues = new HashMap<String, Object>();
ViewComputationResultModel result = client.getLatestResult();
ViewTargetResultModel targetResult = result.getTargetResult(ViewProcessorTestEnvironment.getPrimitive1().getTargetSpecification());
for (ComputedValue computedValue : targetResult.getAllValues(ViewProcessorTestEnvironment.TEST_CALC_CONFIG_NAME)) {
resultValues.put(computedValue.getSpecification().getValueName(), computedValue.getValue());
}
assertEquals(123d, resultValues.get(ViewProcessorTestEnvironment.getPrimitive1().getValueName()));
assertEquals(456d, resultValues.get(ViewProcessorTestEnvironment.getPrimitive2().getValueName()));
resultListener.assertProcessCompleted(TIMEOUT);
assertThreadReachesState(recalcThread, Thread.State.TERMINATED);
}
@Test
public void testDoNotWaitForMarketData() throws InterruptedException {
final ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
InMemoryLKVMarketDataProvider underlyingProvider = new InMemoryLKVMarketDataProvider();
MarketDataProvider marketDataProvider = new TestLiveMarketDataProvider("source", underlyingProvider);
env.setMarketDataProvider(marketDataProvider);
env.init();
ViewProcessorImpl vp = env.getViewProcessor();
vp.start();
ViewClient client = vp.createViewClient(ViewProcessorTestEnvironment.TEST_USER);
TestViewResultListener resultListener = new TestViewResultListener();
client.setResultListener(resultListener);
ViewCycleExecutionOptions cycleExecutionOptions = new ViewCycleExecutionOptions(Instant.now(), MarketData.live());
EnumSet<ViewExecutionFlags> flags = ExecutionFlags.none().get();
ViewExecutionOptions executionOptions = ExecutionOptions.of(ArbitraryViewCycleExecutionSequence.single(cycleExecutionOptions), flags);
client.attachToViewProcess(env.getViewDefinition().getName(), executionOptions);
resultListener.assertViewDefinitionCompiled(TIMEOUT);
resultListener.assertCycleCompleted(TIMEOUT);
resultListener.assertProcessCompleted(TIMEOUT);
ViewComputationResultModel result = client.getLatestResult();
ViewTargetResultModel targetResult = result.getTargetResult(ViewProcessorTestEnvironment.getPrimitive1().getTargetSpecification());
assertNull(targetResult);
}
@Test
public void testChangeMarketDataProviderBetweenCycles() throws InterruptedException {
ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
InMemoryLKVMarketDataProvider underlyingProvider1 = new InMemoryLKVMarketDataProvider();
MarketDataProvider provider1 = new TestLiveMarketDataProvider(SOURCE_1_NAME, underlyingProvider1);
InMemoryLKVMarketDataProvider underlyingProvider2 = new InMemoryLKVMarketDataProvider();
MarketDataProvider provider2 = new TestLiveMarketDataProvider(SOURCE_2_NAME, underlyingProvider2);
env.setMarketDataProviderResolver(new DualLiveMarketDataProviderResolver(SOURCE_1_NAME, provider1, SOURCE_2_NAME, provider2));
env.init();
ViewProcessorImpl vp = env.getViewProcessor();
vp.start();
ViewClient client = vp.createViewClient(ViewProcessorTestEnvironment.TEST_USER);
TestViewResultListener resultListener = new TestViewResultListener();
client.setResultListener(resultListener);
Instant valuationTime = Instant.now();
ViewCycleExecutionOptions cycle1 = new ViewCycleExecutionOptions(valuationTime, MarketData.live(SOURCE_1_NAME));
ViewCycleExecutionOptions cycle2 = new ViewCycleExecutionOptions(valuationTime, MarketData.live(SOURCE_2_NAME));
EnumSet<ViewExecutionFlags> flags = ExecutionFlags.none().runAsFastAsPossible().get();
ViewExecutionOptions executionOptions = ExecutionOptions.of(ArbitraryViewCycleExecutionSequence.of(cycle1, cycle2), flags);
client.attachToViewProcess(env.getViewDefinition().getName(), executionOptions);
resultListener.assertViewDefinitionCompiled(TIMEOUT);
resultListener.assertCycleCompleted(TIMEOUT);
resultListener.assertViewDefinitionCompiled(TIMEOUT);
// Change of market data provider should cause a further compilation
resultListener.assertCycleCompleted(TIMEOUT);
resultListener.assertProcessCompleted(TIMEOUT);
}
private void assertThreadReachesState(Thread recalcThread, Thread.State state) throws InterruptedException {
long startTime = System.currentTimeMillis();
while (recalcThread.getState() != state) {
Thread.sleep(50);
if (System.currentTimeMillis() - startTime > TIMEOUT) {
throw new OpenGammaRuntimeException("Waited longer than " + TIMEOUT + " ms for the recalc thread to reach state " + state);
}
}
}
private static class TestLiveMarketDataProvider implements MarketDataProvider, MarketDataAvailabilityProvider {
private final String _sourceName;
private final InMemoryLKVMarketDataProvider _underlyingProvider;
private final LiveDataClient _dummyLiveDataClient = new LiveDataClient() {
@Override
public Map<LiveDataSpecification, Boolean> isEntitled(UserPrincipal user, Collection<LiveDataSpecification> requestedSpecifications) {
return null;
}
@Override
public boolean isEntitled(UserPrincipal user, LiveDataSpecification requestedSpecification) {
return false;
}
@Override
public void unsubscribe(UserPrincipal user, Collection<LiveDataSpecification> fullyQualifiedSpecifications, LiveDataListener listener) {
}
@Override
public void unsubscribe(UserPrincipal user, LiveDataSpecification fullyQualifiedSpecification, LiveDataListener listener) {
}
@Override
public void subscribe(UserPrincipal user, Collection<LiveDataSpecification> requestedSpecifications, LiveDataListener listener) {
}
@Override
public void subscribe(UserPrincipal user, LiveDataSpecification requestedSpecification, LiveDataListener listener) {
}
@Override
public Collection<LiveDataSubscriptionResponse> snapshot(UserPrincipal user, Collection<LiveDataSpecification> requestedSpecifications, long timeout) {
return null;
}
@Override
public LiveDataSubscriptionResponse snapshot(UserPrincipal user, LiveDataSpecification requestedSpecification, long timeout) {
return null;
}
@Override
public String getDefaultNormalizationRuleSetId() {
return null;
}
@Override
public void close() {
}
};
public TestLiveMarketDataProvider(String sourceName, InMemoryLKVMarketDataProvider underlyingProvider) {
ArgumentChecker.notNull(sourceName, "sourceName");
_sourceName = sourceName;
_underlyingProvider = underlyingProvider;
}
@Override
public void addListener(MarketDataListener listener) {
_underlyingProvider.addListener(listener);
}
@Override
public void removeListener(MarketDataListener listener) {
_underlyingProvider.removeListener(listener);
}
@Override
public void subscribe(UserPrincipal user, ValueRequirement valueRequirement) {
_underlyingProvider.subscribe(user, valueRequirement);
}
@Override
public void subscribe(UserPrincipal user, Set<ValueRequirement> valueRequirements) {
_underlyingProvider.subscribe(user, valueRequirements);
}
@Override
public void unsubscribe(UserPrincipal user, ValueRequirement valueRequirement) {
_underlyingProvider.unsubscribe(user, valueRequirement);
}
@Override
public void unsubscribe(UserPrincipal user, Set<ValueRequirement> valueRequirements) {
_underlyingProvider.unsubscribe(user, valueRequirements);
}
@Override
public MarketDataAvailabilityProvider getAvailabilityProvider() {
return this;
}
@Override
public MarketDataPermissionProvider getPermissionProvider() {
return new PermissiveMarketDataPermissionProvider();
}
@Override
public boolean isCompatible(MarketDataSpecification marketDataSpec) {
if (!(marketDataSpec instanceof LiveMarketDataSpecification)) {
return false;
}
LiveMarketDataSpecification liveMarketDataSpec = (LiveMarketDataSpecification) marketDataSpec;
return _sourceName.equals(liveMarketDataSpec.getDataSource());
}
@Override
public MarketDataSnapshot snapshot(MarketDataSpecification marketDataSpec) {
final SecuritySource dummySecuritySource = new MockSecuritySource();
return new LiveMarketDataSnapshot(_underlyingProvider.snapshot(marketDataSpec), new LiveMarketDataProvider(_dummyLiveDataClient, dummySecuritySource, getAvailabilityProvider()));
}
@Override
public boolean isAvailable(ValueRequirement requirement) {
// Want the market data provider to indicate that data is available even before it's really available
return requirement.equals(ViewProcessorTestEnvironment.getPrimitive1())
|| requirement.equals(ViewProcessorTestEnvironment.getPrimitive2());
}
}
private static class DualLiveMarketDataProviderResolver implements MarketDataProviderResolver {
private final String _provider1SourceName;
private final MarketDataProvider _provider1;
private final String _provider2SourceName;
private final MarketDataProvider _provider2;
public DualLiveMarketDataProviderResolver(String provider1SourceName, MarketDataProvider provider1, String provider2SourceName, MarketDataProvider provider2) {
_provider1SourceName = provider1SourceName;
_provider1 = provider1;
_provider2SourceName = provider2SourceName;
_provider2 = provider2;
}
@Override
public MarketDataProvider resolve(MarketDataSpecification snapshotSpec) {
if (_provider1SourceName.equals(((LiveMarketDataSpecification) snapshotSpec).getDataSource())) {
return _provider1;
}
if (_provider2SourceName.equals(((LiveMarketDataSpecification) snapshotSpec).getDataSource())) {
return _provider2;
}
throw new IllegalArgumentException("Unknown data source name");
}
}
}
| projects/OG-Engine/tests/unit/com/opengamma/engine/view/calc/ViewComputationJobTest.java | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.view.calc;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.time.Instant;
import org.testng.annotations.Test;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.engine.marketdata.InMemoryLKVMarketDataProvider;
import com.opengamma.engine.marketdata.MarketDataListener;
import com.opengamma.engine.marketdata.MarketDataProvider;
import com.opengamma.engine.marketdata.MarketDataSnapshot;
import com.opengamma.engine.marketdata.availability.MarketDataAvailabilityProvider;
import com.opengamma.engine.marketdata.permission.MarketDataPermissionProvider;
import com.opengamma.engine.marketdata.permission.PermissiveMarketDataPermissionProvider;
import com.opengamma.engine.marketdata.resolver.MarketDataProviderResolver;
import com.opengamma.engine.marketdata.spec.LiveMarketDataSpecification;
import com.opengamma.engine.marketdata.spec.MarketData;
import com.opengamma.engine.marketdata.spec.MarketDataSpecification;
import com.opengamma.engine.test.TestViewResultListener;
import com.opengamma.engine.test.ViewProcessorTestEnvironment;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.view.ViewComputationResultModel;
import com.opengamma.engine.view.ViewProcessImpl;
import com.opengamma.engine.view.ViewProcessorImpl;
import com.opengamma.engine.view.ViewTargetResultModel;
import com.opengamma.engine.view.client.ViewClient;
import com.opengamma.engine.view.execution.ArbitraryViewCycleExecutionSequence;
import com.opengamma.engine.view.execution.ExecutionFlags;
import com.opengamma.engine.view.execution.ExecutionOptions;
import com.opengamma.engine.view.execution.ViewCycleExecutionOptions;
import com.opengamma.engine.view.execution.ViewExecutionFlags;
import com.opengamma.engine.view.execution.ViewExecutionOptions;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.test.Timeout;
/**
* Tests {@link ViewComputationJob}
*/
public class ViewComputationJobTest {
private static final long TIMEOUT = 10L * Timeout.standardTimeoutMillis();
private static final String SOURCE_1_NAME = "source1";
private static final String SOURCE_2_NAME = "source2";
@Test
public void testInterruptJobBetweenCycles() throws InterruptedException {
// Due to all the dependencies between components for execution to take place, it's easiest to test it in a
// realistic environment. In its default configuration, only live data can trigger a computation cycle (after the
// initial cycle).
ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
env.init();
ViewProcessorImpl vp = env.getViewProcessor();
vp.start();
ViewClient client = vp.createViewClient(ViewProcessorTestEnvironment.TEST_USER);
TestViewResultListener resultListener = new TestViewResultListener();
client.setResultListener(resultListener);
client.attachToViewProcess(env.getViewDefinition().getName(), ExecutionOptions.infinite(MarketData.live()));
// Consume the initial result
resultListener.assertViewDefinitionCompiled(TIMEOUT);
resultListener.assertCycleCompleted(TIMEOUT);
ViewProcessImpl viewProcess = env.getViewProcess(vp, client.getUniqueId());
Thread recalcThread = env.getCurrentComputationThread(viewProcess);
assertThreadReachesState(recalcThread, Thread.State.TIMED_WAITING);
// We're now 'between cycles', waiting for the arrival of live data.
// Interrupting should terminate the job gracefully
ViewComputationJob job = env.getCurrentComputationJob(viewProcess);
job.terminate();
recalcThread.interrupt();
recalcThread.join(TIMEOUT);
assertEquals(Thread.State.TERMINATED, recalcThread.getState());
}
@Test
public void testWaitForMarketData() throws InterruptedException {
final ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
InMemoryLKVMarketDataProvider underlyingProvider = new InMemoryLKVMarketDataProvider();
MarketDataProvider marketDataProvider = new TestLiveMarketDataProvider("source", underlyingProvider);
env.setMarketDataProvider(marketDataProvider);
env.init();
ViewProcessorImpl vp = env.getViewProcessor();
vp.start();
ViewClient client = vp.createViewClient(ViewProcessorTestEnvironment.TEST_USER);
TestViewResultListener resultListener = new TestViewResultListener();
client.setResultListener(resultListener);
ViewCycleExecutionOptions cycleExecutionOptions = new ViewCycleExecutionOptions(Instant.now(), MarketData.live());
EnumSet<ViewExecutionFlags> flags = ExecutionFlags.none().awaitMarketData().get();
ViewExecutionOptions executionOptions = ExecutionOptions.of(ArbitraryViewCycleExecutionSequence.single(cycleExecutionOptions), flags);
client.attachToViewProcess(env.getViewDefinition().getName(), executionOptions);
resultListener.assertViewDefinitionCompiled(TIMEOUT);
ViewProcessImpl viewProcess = env.getViewProcess(vp, client.getUniqueId());
Thread recalcThread = env.getCurrentComputationThread(viewProcess);
assertThreadReachesState(recalcThread, Thread.State.TIMED_WAITING);
underlyingProvider.addValue(ViewProcessorTestEnvironment.getPrimitive1(), 123d);
underlyingProvider.addValue(ViewProcessorTestEnvironment.getPrimitive2(), 456d);
recalcThread.join();
resultListener.assertCycleCompleted(TIMEOUT);
Map<String, Object> resultValues = new HashMap<String, Object>();
ViewComputationResultModel result = client.getLatestResult();
ViewTargetResultModel targetResult = result.getTargetResult(ViewProcessorTestEnvironment.getPrimitive1().getTargetSpecification());
for (ComputedValue computedValue : targetResult.getAllValues(ViewProcessorTestEnvironment.TEST_CALC_CONFIG_NAME)) {
resultValues.put(computedValue.getSpecification().getValueName(), computedValue.getValue());
}
assertEquals(123d, resultValues.get(ViewProcessorTestEnvironment.getPrimitive1().getValueName()));
assertEquals(456d, resultValues.get(ViewProcessorTestEnvironment.getPrimitive2().getValueName()));
resultListener.assertProcessCompleted(TIMEOUT);
assertThreadReachesState(recalcThread, Thread.State.TERMINATED);
}
@Test
public void testDoNotWaitForMarketData() throws InterruptedException {
final ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
InMemoryLKVMarketDataProvider underlyingProvider = new InMemoryLKVMarketDataProvider();
MarketDataProvider marketDataProvider = new TestLiveMarketDataProvider("source", underlyingProvider);
env.setMarketDataProvider(marketDataProvider);
env.init();
ViewProcessorImpl vp = env.getViewProcessor();
vp.start();
ViewClient client = vp.createViewClient(ViewProcessorTestEnvironment.TEST_USER);
TestViewResultListener resultListener = new TestViewResultListener();
client.setResultListener(resultListener);
ViewCycleExecutionOptions cycleExecutionOptions = new ViewCycleExecutionOptions(Instant.now(), MarketData.live());
EnumSet<ViewExecutionFlags> flags = ExecutionFlags.none().get();
ViewExecutionOptions executionOptions = ExecutionOptions.of(ArbitraryViewCycleExecutionSequence.single(cycleExecutionOptions), flags);
client.attachToViewProcess(env.getViewDefinition().getName(), executionOptions);
resultListener.assertViewDefinitionCompiled(TIMEOUT);
resultListener.assertCycleCompleted(TIMEOUT);
resultListener.assertProcessCompleted(TIMEOUT);
ViewComputationResultModel result = client.getLatestResult();
ViewTargetResultModel targetResult = result.getTargetResult(ViewProcessorTestEnvironment.getPrimitive1().getTargetSpecification());
assertNull(targetResult);
}
@Test
public void testChangeMarketDataProviderBetweenCycles() throws InterruptedException {
ViewProcessorTestEnvironment env = new ViewProcessorTestEnvironment();
InMemoryLKVMarketDataProvider underlyingProvider1 = new InMemoryLKVMarketDataProvider();
MarketDataProvider provider1 = new TestLiveMarketDataProvider(SOURCE_1_NAME, underlyingProvider1);
InMemoryLKVMarketDataProvider underlyingProvider2 = new InMemoryLKVMarketDataProvider();
MarketDataProvider provider2 = new TestLiveMarketDataProvider(SOURCE_2_NAME, underlyingProvider2);
env.setMarketDataProviderResolver(new DualLiveMarketDataProviderResolver(SOURCE_1_NAME, provider1, SOURCE_2_NAME, provider2));
env.init();
ViewProcessorImpl vp = env.getViewProcessor();
vp.start();
ViewClient client = vp.createViewClient(ViewProcessorTestEnvironment.TEST_USER);
TestViewResultListener resultListener = new TestViewResultListener();
client.setResultListener(resultListener);
Instant valuationTime = Instant.now();
ViewCycleExecutionOptions cycle1 = new ViewCycleExecutionOptions(valuationTime, MarketData.live(SOURCE_1_NAME));
ViewCycleExecutionOptions cycle2 = new ViewCycleExecutionOptions(valuationTime, MarketData.live(SOURCE_2_NAME));
EnumSet<ViewExecutionFlags> flags = ExecutionFlags.none().runAsFastAsPossible().get();
ViewExecutionOptions executionOptions = ExecutionOptions.of(ArbitraryViewCycleExecutionSequence.of(cycle1, cycle2), flags);
client.attachToViewProcess(env.getViewDefinition().getName(), executionOptions);
resultListener.assertViewDefinitionCompiled(TIMEOUT);
resultListener.assertCycleCompleted(TIMEOUT);
resultListener.assertViewDefinitionCompiled(TIMEOUT);
// Change of market data provider should cause a further compilation
resultListener.assertCycleCompleted(TIMEOUT);
resultListener.assertProcessCompleted(TIMEOUT);
}
private void assertThreadReachesState(Thread recalcThread, Thread.State state) throws InterruptedException {
long startTime = System.currentTimeMillis();
while (recalcThread.getState() != state) {
Thread.sleep(50);
if (System.currentTimeMillis() - startTime > TIMEOUT) {
throw new OpenGammaRuntimeException("Waited longer than " + TIMEOUT + " ms for the recalc thread to reach state " + state);
}
}
}
private static class TestLiveMarketDataProvider implements MarketDataProvider, MarketDataAvailabilityProvider {
private final String _sourceName;
private final InMemoryLKVMarketDataProvider _underlyingProvider;
public TestLiveMarketDataProvider(String sourceName, InMemoryLKVMarketDataProvider underlyingProvider) {
ArgumentChecker.notNull(sourceName, "sourceName");
_sourceName = sourceName;
_underlyingProvider = underlyingProvider;
}
@Override
public void addListener(MarketDataListener listener) {
_underlyingProvider.addListener(listener);
}
@Override
public void removeListener(MarketDataListener listener) {
_underlyingProvider.removeListener(listener);
}
@Override
public void subscribe(UserPrincipal user, ValueRequirement valueRequirement) {
_underlyingProvider.subscribe(user, valueRequirement);
}
@Override
public void subscribe(UserPrincipal user, Set<ValueRequirement> valueRequirements) {
_underlyingProvider.subscribe(user, valueRequirements);
}
@Override
public void unsubscribe(UserPrincipal user, ValueRequirement valueRequirement) {
_underlyingProvider.unsubscribe(user, valueRequirement);
}
@Override
public void unsubscribe(UserPrincipal user, Set<ValueRequirement> valueRequirements) {
_underlyingProvider.unsubscribe(user, valueRequirements);
}
@Override
public MarketDataAvailabilityProvider getAvailabilityProvider() {
return this;
}
@Override
public MarketDataPermissionProvider getPermissionProvider() {
return new PermissiveMarketDataPermissionProvider();
}
@Override
public boolean isCompatible(MarketDataSpecification marketDataSpec) {
if (!(marketDataSpec instanceof LiveMarketDataSpecification)) {
return false;
}
LiveMarketDataSpecification liveMarketDataSpec = (LiveMarketDataSpecification) marketDataSpec;
return _sourceName.equals(liveMarketDataSpec.getDataSource());
}
@Override
public MarketDataSnapshot snapshot(MarketDataSpecification marketDataSpec) {
return _underlyingProvider.snapshot(marketDataSpec);
}
@Override
public boolean isAvailable(ValueRequirement requirement) {
// Want the market data provider to indicate that data is available even before it's really available
return requirement.equals(ViewProcessorTestEnvironment.getPrimitive1())
|| requirement.equals(ViewProcessorTestEnvironment.getPrimitive2());
}
}
private static class DualLiveMarketDataProviderResolver implements MarketDataProviderResolver {
private final String _provider1SourceName;
private final MarketDataProvider _provider1;
private final String _provider2SourceName;
private final MarketDataProvider _provider2;
public DualLiveMarketDataProviderResolver(String provider1SourceName, MarketDataProvider provider1, String provider2SourceName, MarketDataProvider provider2) {
_provider1SourceName = provider1SourceName;
_provider1 = provider1;
_provider2SourceName = provider2SourceName;
_provider2 = provider2;
}
@Override
public MarketDataProvider resolve(MarketDataSpecification snapshotSpec) {
if (_provider1SourceName.equals(((LiveMarketDataSpecification) snapshotSpec).getDataSource())) {
return _provider1;
}
if (_provider2SourceName.equals(((LiveMarketDataSpecification) snapshotSpec).getDataSource())) {
return _provider2;
}
throw new IllegalArgumentException("Unknown data source name");
}
}
}
| [PLAT-1429] Return a LiveMarketDataSnapshot so that wait for market data can be tested; the LKVMarketDataSnapshot no longer blocks.
| projects/OG-Engine/tests/unit/com/opengamma/engine/view/calc/ViewComputationJobTest.java | [PLAT-1429] Return a LiveMarketDataSnapshot so that wait for market data can be tested; the LKVMarketDataSnapshot no longer blocks. | <ide><path>rojects/OG-Engine/tests/unit/com/opengamma/engine/view/calc/ViewComputationJobTest.java
<ide> import static org.testng.AssertJUnit.assertEquals;
<ide> import static org.testng.AssertJUnit.assertNull;
<ide>
<add>import java.util.Collection;
<ide> import java.util.EnumSet;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide> import org.testng.annotations.Test;
<ide>
<ide> import com.opengamma.OpenGammaRuntimeException;
<add>import com.opengamma.core.security.SecuritySource;
<ide> import com.opengamma.engine.marketdata.InMemoryLKVMarketDataProvider;
<add>import com.opengamma.engine.marketdata.LiveMarketDataProvider;
<add>import com.opengamma.engine.marketdata.LiveMarketDataSnapshot;
<ide> import com.opengamma.engine.marketdata.MarketDataListener;
<ide> import com.opengamma.engine.marketdata.MarketDataProvider;
<ide> import com.opengamma.engine.marketdata.MarketDataSnapshot;
<ide> import com.opengamma.engine.marketdata.spec.LiveMarketDataSpecification;
<ide> import com.opengamma.engine.marketdata.spec.MarketData;
<ide> import com.opengamma.engine.marketdata.spec.MarketDataSpecification;
<add>import com.opengamma.engine.test.MockSecuritySource;
<ide> import com.opengamma.engine.test.TestViewResultListener;
<ide> import com.opengamma.engine.test.ViewProcessorTestEnvironment;
<ide> import com.opengamma.engine.value.ComputedValue;
<ide> import com.opengamma.engine.view.execution.ViewCycleExecutionOptions;
<ide> import com.opengamma.engine.view.execution.ViewExecutionFlags;
<ide> import com.opengamma.engine.view.execution.ViewExecutionOptions;
<add>import com.opengamma.livedata.LiveDataClient;
<add>import com.opengamma.livedata.LiveDataListener;
<add>import com.opengamma.livedata.LiveDataSpecification;
<ide> import com.opengamma.livedata.UserPrincipal;
<add>import com.opengamma.livedata.msg.LiveDataSubscriptionResponse;
<ide> import com.opengamma.util.ArgumentChecker;
<ide> import com.opengamma.util.test.Timeout;
<ide>
<ide> */
<ide> public class ViewComputationJobTest {
<ide>
<del> private static final long TIMEOUT = 10L * Timeout.standardTimeoutMillis();
<add> private static final long TIMEOUT = 5L * Timeout.standardTimeoutMillis();
<ide>
<ide> private static final String SOURCE_1_NAME = "source1";
<ide> private static final String SOURCE_2_NAME = "source2";
<ide>
<ide> private final String _sourceName;
<ide> private final InMemoryLKVMarketDataProvider _underlyingProvider;
<add> private final LiveDataClient _dummyLiveDataClient = new LiveDataClient() {
<add>
<add> @Override
<add> public Map<LiveDataSpecification, Boolean> isEntitled(UserPrincipal user, Collection<LiveDataSpecification> requestedSpecifications) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public boolean isEntitled(UserPrincipal user, LiveDataSpecification requestedSpecification) {
<add> return false;
<add> }
<add>
<add> @Override
<add> public void unsubscribe(UserPrincipal user, Collection<LiveDataSpecification> fullyQualifiedSpecifications, LiveDataListener listener) {
<add> }
<add>
<add> @Override
<add> public void unsubscribe(UserPrincipal user, LiveDataSpecification fullyQualifiedSpecification, LiveDataListener listener) {
<add> }
<add>
<add> @Override
<add> public void subscribe(UserPrincipal user, Collection<LiveDataSpecification> requestedSpecifications, LiveDataListener listener) {
<add> }
<add>
<add> @Override
<add> public void subscribe(UserPrincipal user, LiveDataSpecification requestedSpecification, LiveDataListener listener) {
<add> }
<add>
<add> @Override
<add> public Collection<LiveDataSubscriptionResponse> snapshot(UserPrincipal user, Collection<LiveDataSpecification> requestedSpecifications, long timeout) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public LiveDataSubscriptionResponse snapshot(UserPrincipal user, LiveDataSpecification requestedSpecification, long timeout) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public String getDefaultNormalizationRuleSetId() {
<add> return null;
<add> }
<add>
<add> @Override
<add> public void close() {
<add> }
<add>
<add> };
<ide>
<ide> public TestLiveMarketDataProvider(String sourceName, InMemoryLKVMarketDataProvider underlyingProvider) {
<ide> ArgumentChecker.notNull(sourceName, "sourceName");
<ide>
<ide> @Override
<ide> public MarketDataSnapshot snapshot(MarketDataSpecification marketDataSpec) {
<del> return _underlyingProvider.snapshot(marketDataSpec);
<add> final SecuritySource dummySecuritySource = new MockSecuritySource();
<add> return new LiveMarketDataSnapshot(_underlyingProvider.snapshot(marketDataSpec), new LiveMarketDataProvider(_dummyLiveDataClient, dummySecuritySource, getAvailabilityProvider()));
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | c76d68f33dbf2ecbd1e23d4f706fe4a8942e8b57 | 0 | sjnyag/stamp,sjnyag/stamp | package com.sjn.stamp.utils;
import android.content.Context;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.sjn.stamp.ui.activity.DrawerMenu;
import java.util.Date;
import static com.sjn.stamp.utils.MediaIDHelper.getHierarchy;
public class AnalyticsHelper {
private static final String CREATE_STAMP = "create_stamp";
private static final String PLAY_CATEGORY = "play_category";
private static final String CHANGE_SCREEN = "change_screen";
private static final String CHANGE_SETTING = "change_setting";
private static final String CHANGE_RANKING_TERM = "change_ranking_term";
public static void trackCategory(Context context, String mediaId) {
Bundle payload = new Bundle();
String[] hierarchy = getHierarchy(mediaId);
if (hierarchy.length < 1) {
return;
}
String category = hierarchy[0];
payload.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, category);
FirebaseAnalytics.getInstance(context).logEvent(PLAY_CATEGORY, payload);
}
public static void trackScreen(Context context, DrawerMenu drawerMenu) {
if (drawerMenu == null) {
return;
}
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.CONTENT, drawerMenu.toString());
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SCREEN, payload);
}
public static void trackStamp(Context context, String stamp) {
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.ITEM_NAME, stamp);
FirebaseAnalytics.getInstance(context).logEvent(CREATE_STAMP, payload);
}
public static void trackSetting(Context context, String name) {
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SETTING, payload);
}
public static void trackSetting(Context context, String name, String value) {
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
payload.putString(FirebaseAnalytics.Param.VALUE, value);
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SETTING, payload);
}
public static void trackRankingTerm(Context context, Date start, Date end) {
Bundle payload = new Bundle();
if(start != null) {
payload.putString(FirebaseAnalytics.Param.START_DATE, start.toString());
}
if(end != null) {
payload.putString(FirebaseAnalytics.Param.END_DATE, end.toString());
}
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_RANKING_TERM, payload);
}
}
| app/src/main/java/com/sjn/stamp/utils/AnalyticsHelper.java | package com.sjn.stamp.utils;
import android.content.Context;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.sjn.stamp.ui.activity.DrawerMenu;
import java.util.Date;
import static com.sjn.stamp.utils.MediaIDHelper.getHierarchy;
public class AnalyticsHelper {
private static final String CREATE_STAMP = "create_stamp";
private static final String PLAY_CATEGORY = "play_category";
private static final String CHANGE_SCREEN = "change_screen";
private static final String CHANGE_SETTING = "change_setting";
private static final String CHANGE_RANKING_TERM = "change_ranking_term";
public static void trackCategory(Context context, String mediaId) {
Bundle payload = new Bundle();
String[] hierarchy = getHierarchy(mediaId);
if (hierarchy.length < 1) {
return;
}
String category = hierarchy[0];
payload.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, category);
FirebaseAnalytics.getInstance(context).logEvent(PLAY_CATEGORY, payload);
}
public static void trackScreen(Context context, DrawerMenu drawerMenu) {
if (drawerMenu == null) {
return;
}
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.CONTENT, drawerMenu.toString());
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SCREEN, payload);
}
public static void trackStamp(Context context, String stamp) {
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.ITEM_NAME, stamp);
FirebaseAnalytics.getInstance(context).logEvent(CREATE_STAMP, payload);
}
public static void trackSetting(Context context, String name) {
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SETTING, payload);
}
public static void trackSetting(Context context, String name, String value) {
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
payload.putString(FirebaseAnalytics.Param.VALUE, value);
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_SETTING, payload);
}
public static void trackRankingTerm(Context context, Date start, Date end) {
Bundle payload = new Bundle();
payload.putString(FirebaseAnalytics.Param.START_DATE, start.toString());
payload.putString(FirebaseAnalytics.Param.END_DATE, end.toString());
FirebaseAnalytics.getInstance(context).logEvent(CHANGE_RANKING_TERM, payload);
}
}
| bug fix of tracking ranking term
| app/src/main/java/com/sjn/stamp/utils/AnalyticsHelper.java | bug fix of tracking ranking term | <ide><path>pp/src/main/java/com/sjn/stamp/utils/AnalyticsHelper.java
<ide>
<ide> public static void trackRankingTerm(Context context, Date start, Date end) {
<ide> Bundle payload = new Bundle();
<del> payload.putString(FirebaseAnalytics.Param.START_DATE, start.toString());
<del> payload.putString(FirebaseAnalytics.Param.END_DATE, end.toString());
<add> if(start != null) {
<add> payload.putString(FirebaseAnalytics.Param.START_DATE, start.toString());
<add> }
<add> if(end != null) {
<add> payload.putString(FirebaseAnalytics.Param.END_DATE, end.toString());
<add> }
<ide> FirebaseAnalytics.getInstance(context).logEvent(CHANGE_RANKING_TERM, payload);
<ide> }
<ide> } |
|
JavaScript | mit | d1967d94474f3f20397d7e0649fdf80e8f8e4991 | 0 | varung-optimus/uppy,transloadit/uppy,varung-optimus/uppy,transloadit/uppy,transloadit/uppy,varung-optimus/uppy,transloadit/uppy | import Plugin from './Plugin'
import tus from 'tus-js-client'
import UppySocket from '../core/UppySocket'
/**
* Tus resumable file uploader
*
*/
export default class Tus10 extends Plugin {
constructor (core, opts) {
super(core, opts)
this.type = 'uploader'
this.id = 'Tus'
this.title = 'Tus'
// set default options
const defaultOptions = {}
// merge default options with the ones set by user
this.opts = Object.assign({}, defaultOptions, opts)
}
/**
* Create a new Tus upload
*
* @param {object} file for use with upload
* @param {integer} current file in a queue
* @param {integer} total number of files in a queue
* @returns {Promise}
*/
upload (file, current, total) {
this.core.log(`uploading ${current} of ${total}`)
// Create a new tus upload
return new Promise((resolve, reject) => {
const upload = new tus.Upload(file.data, {
// TODO merge this.opts or this.opts.tus here
metadata: file.meta,
resume: false,
endpoint: this.opts.endpoint,
onError: (error) => {
reject('Failed because: ' + error)
},
onProgress: (bytesUploaded, bytesTotal) => {
// Dispatch progress event
this.core.emitter.emit('upload-progress', {
uploader: this,
id: file.id,
bytesUploaded: bytesUploaded,
bytesTotal: bytesTotal
})
},
onSuccess: () => {
// file.uploadURL = upload.url
this.core.emitter.emit('upload-success', file.id, upload.url)
this.core.log(`Download ${upload.file.name} from ${upload.url}`)
resolve(upload)
}
})
this.core.emitter.on('file-remove', (fileID) => {
if (fileID === file.id) {
upload.abort()
}
})
upload.start()
})
}
uploadRemote (file, current, total) {
return new Promise((resolve, reject) => {
console.log(file.remote.url)
fetch(file.remote.url, {
method: 'post',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(Object.assign({}, file.remote.body, {
target: this.opts.endpoint,
protocol: 'tus'
}))
})
.then((res) => {
if (res.status < 200 && res.status > 300) {
return reject(res.statusText)
}
res.json()
.then((data) => {
// get the host domain
var regex = /^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)/
var host = regex.exec(file.remote.host)[1]
var token = data.token
var socket = new UppySocket({
target: `ws://${host}:3121/api/${token}`
})
socket.on('progress', (progressData) => {
if (progressData.complete) {
this.core.log(`Remote upload of '${file.name}' successful`)
this.core.emitter.emit('upload-success', file)
return resolve('Success')
}
if (progressData.progress) {
this.core.log(`Upload progress: ${progressData.progress}`)
// Dispatch progress event
this.core.emitter.emit('upload-progress', {
uploader: this,
id: file.id,
bytesUploaded: progressData.bytesUploaded,
bytesTotal: progressData.bytesTotal
})
}
})
})
})
})
}
uploadFiles (files) {
const uploaders = []
files.forEach((file, index) => {
const current = parseInt(index, 10) + 1
const total = files.length
if (!file.isRemote) {
uploaders.push(this.upload(file, current, total))
} else {
uploaders.push(this.uploadRemote(file, current, total))
}
})
return Promise.all(uploaders).then(() => {
return {
uploadedCount: files.length
}
})
}
selectForUpload (files) {
// TODO: replace files[file].isRemote with some logic
//
// filter files that are now yet being uploaded / haven’t been uploaded
// and remote too
const filesForUpload = Object.keys(files).filter((file) => {
if (files[file].progress === 0 || files[file].isRemote) {
return true
}
return false
}).map((file) => {
return files[file]
})
this.uploadFiles(filesForUpload)
}
install () {
this.core.emitter.on('next', () => {
this.core.log('Tus is uploading...')
const files = this.core.state.files
this.selectForUpload(files)
})
}
}
| src/plugins/Tus10.js | import Plugin from './Plugin'
import tus from 'tus-js-client'
import UppySocket from '../core/UppySocket'
/**
* Tus resumable file uploader
*
*/
export default class Tus10 extends Plugin {
constructor (core, opts) {
super(core, opts)
this.type = 'uploader'
this.id = 'Tus'
this.title = 'Tus'
// set default options
const defaultOptions = {}
// merge default options with the ones set by user
this.opts = Object.assign({}, defaultOptions, opts)
}
/**
* Create a new Tus upload
*
* @param {object} file for use with upload
* @param {integer} current file in a queue
* @param {integer} total number of files in a queue
* @returns {Promise}
*/
upload (file, current, total) {
this.core.log(`uploading ${current} of ${total}`)
// Create a new tus upload
return new Promise((resolve, reject) => {
const upload = new tus.Upload(file.data, {
// TODO merge this.opts or this.opts.tus here
resume: false,
endpoint: this.opts.endpoint,
onError: (error) => {
reject('Failed because: ' + error)
},
onProgress: (bytesUploaded, bytesTotal) => {
// Dispatch progress event
this.core.emitter.emit('upload-progress', {
uploader: this,
id: file.id,
bytesUploaded: bytesUploaded,
bytesTotal: bytesTotal
})
},
onSuccess: () => {
file.uploadURL = upload.url
this.core.emitter.emit('upload-success', file)
this.core.log(`Download ${upload.file.name} from ${upload.url}`)
resolve(upload)
}
})
this.core.emitter.on('file-remove', (fileID) => {
if (fileID === file.id) {
upload.abort()
}
})
upload.start()
})
}
uploadRemote (file, current, total) {
return new Promise((resolve, reject) => {
console.log(file.remote.url)
fetch(file.remote.url, {
method: 'post',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(Object.assign({}, file.remote.body, {
target: this.opts.endpoint,
protocol: 'tus'
}))
})
.then((res) => {
if (res.status < 200 && res.status > 300) {
return reject(res.statusText)
}
res.json()
.then((data) => {
// get the host domain
var regex = /^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)/
var host = regex.exec(file.remote.host)[1]
var token = data.token
var socket = new UppySocket({
target: `ws://${host}:3121/api/${token}`
})
socket.on('progress', (progressData) => {
if (progressData.complete) {
this.core.log(`Remote upload of '${file.name}' successful`)
this.core.emitter.emit('upload-success', file)
return resolve('Success')
}
if (progressData.progress) {
this.core.log(`Upload progress: ${progressData.progress}`)
// Dispatch progress event
this.core.emitter.emit('upload-progress', {
uploader: this,
id: file.id,
bytesUploaded: progressData.bytesUploaded,
bytesTotal: progressData.bytesTotal
})
}
})
})
})
})
}
uploadFiles (files) {
const uploaders = []
files.forEach((file, index) => {
const current = parseInt(index, 10) + 1
const total = files.length
if (!file.isRemote) {
uploaders.push(this.upload(file, current, total))
} else {
uploaders.push(this.uploadRemote(file, current, total))
}
})
return Promise.all(uploaders).then(() => {
return {
uploadedCount: files.length
}
})
}
selectForUpload (files) {
// TODO: replace files[file].isRemote with some logic
//
// filter files that are now yet being uploaded / haven’t been uploaded
// and remote too
const filesForUpload = Object.keys(files).filter((file) => {
if (files[file].progress === 0 || files[file].isRemote) {
return true
}
return false
}).map((file) => {
return files[file]
})
this.uploadFiles(filesForUpload)
}
install () {
this.core.emitter.on('next', () => {
this.core.log('Tus is uploading...')
const files = this.core.state.files
this.selectForUpload(files)
})
}
}
| add metadata to tus uploads
| src/plugins/Tus10.js | add metadata to tus uploads | <ide><path>rc/plugins/Tus10.js
<ide> const upload = new tus.Upload(file.data, {
<ide>
<ide> // TODO merge this.opts or this.opts.tus here
<add> metadata: file.meta,
<ide> resume: false,
<ide> endpoint: this.opts.endpoint,
<ide> onError: (error) => {
<ide> })
<ide> },
<ide> onSuccess: () => {
<del> file.uploadURL = upload.url
<del> this.core.emitter.emit('upload-success', file)
<add> // file.uploadURL = upload.url
<add> this.core.emitter.emit('upload-success', file.id, upload.url)
<ide>
<ide> this.core.log(`Download ${upload.file.name} from ${upload.url}`)
<ide> resolve(upload) |
|
Java | mit | d723bfa84d6a92556c5f796cd6f9364960215f82 | 0 | smarr/SOMns-vscode,smarr/SOMns-vscode,smarr/SOMns-vscode | package som.langserv.som;
import java.util.Objects;
import som.langserv.structure.LanguageElementId;
import trufflesom.compiler.Field;
public class FieldId extends LanguageElementId {
private transient final Field field;
private final int fieldIndex;
public FieldId(final Field field) {
this.field = field;
this.fieldIndex = field.getIndex();
}
public FieldId(final int fieldIndex) {
this.field = null;
this.fieldIndex = fieldIndex;
}
@Override
protected String getName() {
if (field == null) {
return "" + fieldIndex;
}
return field.getName().getString();
}
@Override
public int hashCode() {
return Objects.hash(fieldIndex);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FieldId other = (FieldId) obj;
if (field == null || other.field == null) {
return fieldIndex == other.fieldIndex;
}
return field == other.field;
}
}
| server/src/som/langserv/som/FieldId.java | package som.langserv.som;
import java.util.Objects;
import som.langserv.structure.LanguageElementId;
import trufflesom.compiler.Field;
public class FieldId extends LanguageElementId {
private transient final Field field;
private final int fieldIndex;
public FieldId(final Field field) {
this.field = field;
this.fieldIndex = field.getIndex();
}
public FieldId(final int fieldIndex) {
this.field = null;
this.fieldIndex = fieldIndex;
}
@Override
protected String getName() {
return field.getName().getString();
}
@Override
public int hashCode() {
return Objects.hash(field, fieldIndex);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FieldId other = (FieldId) obj;
return field == other.field && fieldIndex == other.fieldIndex;
}
}
| FieldId may be obtained with just the index, need to consider that for equality+hash, and make it weaker
Signed-off-by: Stefan Marr <[email protected]>
| server/src/som/langserv/som/FieldId.java | FieldId may be obtained with just the index, need to consider that for equality+hash, and make it weaker | <ide><path>erver/src/som/langserv/som/FieldId.java
<ide>
<ide> @Override
<ide> protected String getName() {
<add> if (field == null) {
<add> return "" + fieldIndex;
<add> }
<ide> return field.getName().getString();
<ide> }
<ide>
<ide> @Override
<ide> public int hashCode() {
<del> return Objects.hash(field, fieldIndex);
<add> return Objects.hash(fieldIndex);
<ide> }
<ide>
<ide> @Override
<ide> return false;
<ide> }
<ide> FieldId other = (FieldId) obj;
<del> return field == other.field && fieldIndex == other.fieldIndex;
<add>
<add> if (field == null || other.field == null) {
<add> return fieldIndex == other.fieldIndex;
<add> }
<add> return field == other.field;
<ide> }
<ide> } |
|
JavaScript | bsd-3-clause | 55d9ac360453a3edd39710f587b4c19917ef5fc3 | 0 | ipython/ipython,ipython/ipython | //----------------------------------------------------------------------------
// Copyright (C) 2013 The IPython Development Team
//
// Distributed under the terms of the BSD License. The full license is in
// the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------
//============================================================================
// WidgetModel, WidgetView, and WidgetManager
//============================================================================
/**
* Base Widget classes
* @module IPython
* @namespace IPython
* @submodule widget
*/
(function () {
"use strict";
// Use require.js 'define' method so that require.js is intelligent enough to
// syncronously load everything within this file when it is being 'required'
// elsewhere.
define(["underscore",
"backbone",
], function (_, Backbone) {
//--------------------------------------------------------------------
// WidgetManager class
//--------------------------------------------------------------------
var WidgetManager = function (comm_manager) {
// Public constructor
WidgetManager._managers.push(this);
// Attach a comm manager to the
this.comm_manager = comm_manager;
this._models = {}; /* Dictionary of model ids and model instances */
// Register already-registered widget model types with the comm manager.
var that = this;
_.each(WidgetManager._model_types, function(model_type, model_name) {
that.comm_manager.register_target(model_name, $.proxy(that._handle_comm_open, that));
});
};
//--------------------------------------------------------------------
// Class level
//--------------------------------------------------------------------
WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
WidgetManager._managers = []; /* List of widget managers */
WidgetManager.register_widget_model = function (model_name, model_type) {
// Registers a widget model by name.
WidgetManager._model_types[model_name] = model_type;
// Register the widget with the comm manager. Make sure to pass this object's context
// in so `this` works in the call back.
_.each(WidgetManager._managers, function(instance, i) {
if (instance.comm_manager !== null) {
instance.comm_manager.register_target(model_name, $.proxy(instance._handle_comm_open, instance));
}
});
};
WidgetManager.register_widget_view = function (view_name, view_type) {
// Registers a widget view by name.
WidgetManager._view_types[view_name] = view_type;
};
//--------------------------------------------------------------------
// Instance level
//--------------------------------------------------------------------
WidgetManager.prototype.display_view = function(msg, model) {
// Displays a view for a particular model.
var cell = this.get_msg_cell(msg.parent_header.msg_id);
if (cell === null) {
console.log("Could not determine where the display" +
" message was from. Widget will not be displayed");
} else {
var view = this.create_view(model, {cell: cell});
if (view === null) {
console.error("View creation failed", model);
}
if (cell.widget_subarea) {
cell.widget_area.show();
this._handle_display_view(view);
cell.widget_subarea.append(view.$el);
}
}
};
WidgetManager.prototype._handle_display_view = function (view) {
// Have the IPython keyboard manager disable its event
// handling so the widget can capture keyboard input.
// Note, this is only done on the outer most widgets.
IPython.keyboard_manager.register_events(view.$el);
if (view.additional_elements) {
for (var i = 0; i < view.additional_elements.length; i++) {
IPython.keyboard_manager.register_events(view.additional_elements[i]);
}
}
};
WidgetManager.prototype.create_view = function(model, options, view) {
// Creates a view for a particular model.
var view_name = model.get('_view_name');
var ViewType = WidgetManager._view_types[view_name];
if (ViewType) {
// If a view is passed into the method, use that view's cell as
// the cell for the view that is created.
options = options || {};
if (view !== undefined) {
options.cell = view.options.cell;
}
// Create and render the view...
var parameters = {model: model, options: options};
view = new ViewType(parameters);
view.render();
model.on('destroy', view.remove, view);
return view;
}
return null;
};
WidgetManager.prototype.get_msg_cell = function (msg_id) {
var cell = null;
// First, check to see if the msg was triggered by cell execution.
if (IPython.notebook) {
cell = IPython.notebook.get_msg_cell(msg_id);
}
if (cell !== null) {
return cell;
}
// Second, check to see if a get_cell callback was defined
// for the message. get_cell callbacks are registered for
// widget messages, so this block is actually checking to see if the
// message was triggered by a widget.
var kernel = this.comm_manager.kernel;
if (kernel) {
var callbacks = kernel.get_callbacks_for_msg(msg_id);
if (callbacks && callbacks.iopub &&
callbacks.iopub.get_cell !== undefined) {
return callbacks.iopub.get_cell();
}
}
// Not triggered by a cell or widget (no get_cell callback
// exists).
return null;
};
WidgetManager.prototype.callbacks = function (view) {
// callback handlers specific a view
var callbacks = {};
if (view && view.options.cell) {
// Try to get output handlers
var cell = view.options.cell;
var handle_output = null;
var handle_clear_output = null;
if (cell.output_area) {
handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
}
// Create callback dict using what is known
var that = this;
callbacks = {
iopub : {
output : handle_output,
clear_output : handle_clear_output,
// Special function only registered by widget messages.
// Allows us to get the cell for a message so we know
// where to add widgets if the code requires it.
get_cell : function () {
return cell;
},
},
};
}
return callbacks;
};
WidgetManager.prototype.get_model = function (model_id) {
// Look-up a model instance by its id.
var model = this._models[model_id];
if (model !== undefined && model.id == model_id) {
return model;
}
return null;
};
WidgetManager.prototype._handle_comm_open = function (comm, msg) {
// Handle when a comm is opened.
var that = this;
var model_id = comm.comm_id;
var widget_type_name = msg.content.target_name;
var widget_model = new WidgetManager._model_types[widget_type_name](this, model_id, comm);
widget_model.on('comm:close', function () {
delete that._models[model_id];
});
this._models[model_id] = widget_model;
};
IPython.WidgetManager = WidgetManager;
return IPython.WidgetManager;
});
}());
| IPython/html/static/widgets/js/manager.js | //----------------------------------------------------------------------------
// Copyright (C) 2013 The IPython Development Team
//
// Distributed under the terms of the BSD License. The full license is in
// the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------
//============================================================================
// WidgetModel, WidgetView, and WidgetManager
//============================================================================
/**
* Base Widget classes
* @module IPython
* @namespace IPython
* @submodule widget
*/
(function () {
"use strict";
// Use require.js 'define' method so that require.js is intelligent enough to
// syncronously load everything within this file when it is being 'required'
// elsewhere.
define(["underscore",
"backbone",
], function (_, Backbone) {
//--------------------------------------------------------------------
// WidgetManager class
//--------------------------------------------------------------------
var WidgetManager = function (comm_manager) {
// Public constructor
WidgetManager._managers.push(this);
// Attach a comm manager to the
this.comm_manager = comm_manager;
this._models = {}; /* Dictionary of model ids and model instances */
// Register already-registered widget model types with the comm manager.
var that = this;
_.each(WidgetManager._model_types, function(model_type, model_name) {
that.comm_manager.register_target(model_name, $.proxy(that._handle_comm_open, that));
});
};
//--------------------------------------------------------------------
// Class level
//--------------------------------------------------------------------
WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
WidgetManager._managers = []; /* List of widget managers */
WidgetManager.register_widget_model = function (model_name, model_type) {
// Registers a widget model by name.
WidgetManager._model_types[model_name] = model_type;
// Register the widget with the comm manager. Make sure to pass this object's context
// in so `this` works in the call back.
_.each(WidgetManager._managers, function(instance, i) {
if (instance.comm_manager !== null) {
instance.comm_manager.register_target(model_name, $.proxy(instance._handle_comm_open, instance));
}
});
};
WidgetManager.register_widget_view = function (view_name, view_type) {
// Registers a widget view by name.
WidgetManager._view_types[view_name] = view_type;
};
//--------------------------------------------------------------------
// Instance level
//--------------------------------------------------------------------
WidgetManager.prototype.display_view = function(msg, model) {
// Displays a view for a particular model.
var cell = this.get_msg_cell(msg.parent_header.msg_id);
if (cell === null) {
console.log("Could not determine where the display" +
" message was from. Widget will not be displayed");
} else {
var view = this.create_view(model, {cell: cell});
if (view === null) {
console.error("View creation failed", model);
}
if (cell.widget_subarea) {
cell.widget_area.show();
this._handle_display_view(view);
cell.widget_subarea.append(view.$el);
}
}
};
WidgetManager.prototype._handle_display_view = function (view) {
// Have the IPython keyboard manager disable its event
// handling so the widget can capture keyboard input.
// Note, this is only done on the outer most widgets.
IPython.keyboard_manager.register_events(view.$el);
if (view.additional_elements) {
for (var i = 0; i < view.additional_elements.length; i++) {
IPython.keyboard_manager.register_events(view.additional_elements[i]);
}
}
};
WidgetManager.prototype.create_view = function(model, options, view) {
// Creates a view for a particular model.
var view_name = model.get('_view_name');
var ViewType = WidgetManager._view_types[view_name];
if (ViewType) {
// If a view is passed into the method, use that view's cell as
// the cell for the view that is created.
options = options || {};
if (view !== undefined) {
options.cell = view.options.cell;
}
// Create and render the view...
var parameters = {model: model, options: options};
view = new ViewType(parameters);
view.render();
model.on('destroy', view.remove, view);
return view;
}
return null;
};
WidgetManager.prototype.get_msg_cell = function (msg_id) {
var cell = null;
// First, check to see if the msg was triggered by cell execution.
if (IPython.notebook) {
cell = IPython.notebook.get_msg_cell(msg_id);
}
if (cell !== null) {
return cell;
}
// Second, check to see if a get_cell callback was defined
// for the message. get_cell callbacks are registered for
// widget messages, so this block is actually checking to see if the
// message was triggered by a widget.
var kernel = this.comm_manager.kernel;
if (kernel) {
var callbacks = kernel.get_callbacks_for_msg(msg_id);
if (callbacks && callbacks.iopub &&
callbacks.iopub.get_cell !== undefined) {
return callbacks.iopub.get_cell();
}
}
// Not triggered by a cell or widget (no get_cell callback
// exists).
return null;
};
WidgetManager.prototype.callbacks = function (view) {
// callback handlers specific a view
var callbacks = {};
if (view && view.options.cell) {
// Try to get output handlers
var cell = view.options.cell;
var handle_output = null;
var handle_clear_output = null;
if (cell.output_area) {
handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
}
// Create callback dict using what is known
var that = this;
callbacks = {
iopub : {
output : handle_output,
clear_output : handle_clear_output,
// Special function only registered by widget messages.
// Allows us to get the cell for a message so we know
// where to add widgets if the code requires it.
get_cell : function () {
return cell;
},
},
};
}
return callbacks;
};
WidgetManager.prototype.get_model = function (model_id) {
// Look-up a model instance by its id.
var model = this._models[model_id];
if (model !== undefined && model.id == model_id) {
return model;
}
return null;
};
WidgetManager.prototype._handle_comm_open = function (comm, msg) {
// Handle when a comm is opened.
var model_id = comm.comm_id;
var widget_type_name = msg.content.target_name;
var widget_model = new WidgetManager._model_types[widget_type_name](this, model_id, comm);
this._models[model_id] = widget_model;
};
IPython.WidgetManager = WidgetManager;
return IPython.WidgetManager;
});
}());
| Remove model from WidgetManager._model on comm:close.
| IPython/html/static/widgets/js/manager.js | Remove model from WidgetManager._model on comm:close. | <ide><path>Python/html/static/widgets/js/manager.js
<ide>
<ide> WidgetManager.prototype._handle_comm_open = function (comm, msg) {
<ide> // Handle when a comm is opened.
<add> var that = this;
<ide> var model_id = comm.comm_id;
<ide> var widget_type_name = msg.content.target_name;
<ide> var widget_model = new WidgetManager._model_types[widget_type_name](this, model_id, comm);
<add> widget_model.on('comm:close', function () {
<add> delete that._models[model_id];
<add> });
<ide> this._models[model_id] = widget_model;
<ide> };
<ide> |
|
Java | apache-2.0 | 239c4faf0e8c254ddb07ce6c0d11dfcf5a742159 | 0 | fabric8io/kubernetes-client,rhuss/kubernetes-client,KurtStam/kubernetes-client,KurtStam/kubernetes-client,rhuss/kubernetes-client,rhuss/kubernetes-client,fabric8io/kubernetes-client,fabric8io/kubernetes-client,KurtStam/kubernetes-client | /**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.client.dsl.internal;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.LogWatch;
import io.fabric8.kubernetes.client.utils.InputStreamPumper;
import io.fabric8.kubernetes.client.utils.Utils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.fabric8.kubernetes.client.utils.Utils.closeQuietly;
import static io.fabric8.kubernetes.client.utils.Utils.shutdownExecutorService;
public class LogWatchCallback implements LogWatch, Callback, AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(LogWatchCallback.class);
private final Config config;
private final OutputStream out;
private final PipedInputStream output;
private final Set<Closeable> toClose = new LinkedHashSet<>();
private final AtomicBoolean started = new AtomicBoolean(false);
private final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(1);
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
private final AtomicBoolean closed = new AtomicBoolean(false);
private InputStreamPumper pumper;
@Deprecated
public LogWatchCallback(OutputStream out) {
this(new Config(), out);
}
public LogWatchCallback(Config config, OutputStream out) {
this.config = config;
if (out == null) {
this.out = new PipedOutputStream();
this.output = new PipedInputStream();
toClose.add(this.out);
toClose.add(this.output);
} else {
this.out = out;
this.output = null;
}
//We need to connect the pipe here, because onResponse might not be called in time (if log is empty)
//This will cause a `Pipe not connected` exception for everyone that tries to read. By always opening
//the pipe the user will get a ready to use inputstream, which will block until there is actually something to read.
if (this.out instanceof PipedOutputStream && this.output != null) {
try {
this.output.connect((PipedOutputStream) this.out);
} catch (IOException e) {
throw KubernetesClientException.launderThrowable(e);
}
}
}
@Override
public void close() {
cleanUp();
}
/**
* Performs the cleanup tasks:
* 1. closes the InputStream pumper
* 2. closes all internally managed closeables (piped streams).
*
* The order of these tasks can't change or its likely that the pumper will through errors,
* if the stream it uses closes before the pumper it self.
*/
private void cleanUp() {
try {
if (!closed.compareAndSet(false, true)) {
return;
}
closeQuietly(pumper);
shutdownExecutorService(executorService);
} finally {
closeQuietly(toClose);
}
}
public void waitUntilReady() {
if (!Utils.waitUntilReady(queue, config.getRequestTimeout(), TimeUnit.MILLISECONDS)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.warn("Log watch request has not been opened within: " + config.getRequestTimeout() + " millis.");
}
}
}
public InputStream getOutput() {
return output;
}
@Override
public void onFailure(Call call, IOException ioe) {
//If we have closed the watch ignore everything
if (closed.get()) {
return;
}
LOGGER.error("Log Callback Failure.", ioe);
//We only need to queue startup failures.
if (!started.get()) {
queue.add(ioe);
}
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
pumper = new InputStreamPumper(response.body().byteStream(), new io.fabric8.kubernetes.client.Callback<byte[]>(){
@Override
public void call(byte[] input) {
try {
out.write(input);
} catch (IOException e) {
throw KubernetesClientException.launderThrowable(e);
}
}
}, new Runnable() {
@Override
public void run() {
response.close();
}
});
executorService.submit(pumper);
started.set(true);
queue.add(true);
}
}
| kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/LogWatchCallback.java | /**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.client.dsl.internal;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.LogWatch;
import io.fabric8.kubernetes.client.utils.InputStreamPumper;
import io.fabric8.kubernetes.client.utils.Utils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.fabric8.kubernetes.client.utils.Utils.closeQuietly;
import static io.fabric8.kubernetes.client.utils.Utils.shutdownExecutorService;
public class LogWatchCallback implements LogWatch, Callback, AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(LogWatchCallback.class);
private final Config config;
private final OutputStream out;
private final PipedInputStream output;
private final Set<Closeable> toClose = new LinkedHashSet<>();
private final AtomicBoolean started = new AtomicBoolean(false);
private final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(1);
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
private final AtomicBoolean closed = new AtomicBoolean(false);
private InputStreamPumper pumper;
@Deprecated
public LogWatchCallback(OutputStream out) {
this(new Config(), out);
}
public LogWatchCallback(Config config, OutputStream out) {
this.config = config;
if (out == null) {
this.out = new PipedOutputStream();
this.output = new PipedInputStream();
toClose.add(out);
toClose.add(output);
} else {
this.out = out;
this.output = null;
}
//We need to connect the pipe here, because onResponse might not be called in time (if log is empty)
//This will cause a `Pipe not connected` exception for everyone that tries to read. By always opening
//the pipe the user will get a ready to use inputstream, which will block until there is actually something to read.
if (out instanceof PipedOutputStream && output != null) {
try {
output.connect((PipedOutputStream) out);
} catch (IOException e) {
throw KubernetesClientException.launderThrowable(e);
}
}
}
@Override
public void close() {
cleanUp();
}
/**
* Performs the cleanup tasks:
* 1. closes the InputStream pumper
* 2. closes all internally managed closeables (piped streams).
*
* The order of these tasks can't change or its likely that the pumper will through errors,
* if the stream it uses closes before the pumper it self.
*/
private void cleanUp() {
try {
if (!closed.compareAndSet(false, true)) {
return;
}
closeQuietly(pumper);
shutdownExecutorService(executorService);
} finally {
closeQuietly(toClose);
}
}
public void waitUntilReady() {
if (!Utils.waitUntilReady(queue, config.getRequestTimeout(), TimeUnit.MILLISECONDS)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.warn("Log watch request has not been opened within: " + config.getRequestTimeout() + " millis.");
}
}
}
public InputStream getOutput() {
return output;
}
@Override
public void onFailure(Call call, IOException ioe) {
//If we have closed the watch ignore everything
if (closed.get()) {
return;
}
LOGGER.error("Log Callback Failure.", ioe);
//We only need to queue startup failures.
if (!started.get()) {
queue.add(ioe);
}
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
pumper = new InputStreamPumper(response.body().byteStream(), new io.fabric8.kubernetes.client.Callback<byte[]>(){
@Override
public void call(byte[] input) {
try {
out.write(input);
} catch (IOException e) {
throw KubernetesClientException.launderThrowable(e);
}
}
}, new Runnable() {
@Override
public void run() {
response.close();
}
});
executorService.submit(pumper);
started.set(true);
queue.add(true);
}
}
| Fix the log watcher
| kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/LogWatchCallback.java | Fix the log watcher | <ide><path>ubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/LogWatchCallback.java
<ide> if (out == null) {
<ide> this.out = new PipedOutputStream();
<ide> this.output = new PipedInputStream();
<del> toClose.add(out);
<del> toClose.add(output);
<add> toClose.add(this.out);
<add> toClose.add(this.output);
<ide> } else {
<ide> this.out = out;
<ide> this.output = null;
<ide> //We need to connect the pipe here, because onResponse might not be called in time (if log is empty)
<ide> //This will cause a `Pipe not connected` exception for everyone that tries to read. By always opening
<ide> //the pipe the user will get a ready to use inputstream, which will block until there is actually something to read.
<del> if (out instanceof PipedOutputStream && output != null) {
<add> if (this.out instanceof PipedOutputStream && this.output != null) {
<ide> try {
<del> output.connect((PipedOutputStream) out);
<add> this.output.connect((PipedOutputStream) this.out);
<ide> } catch (IOException e) {
<ide> throw KubernetesClientException.launderThrowable(e);
<ide> } |
|
Java | apache-2.0 | ab18e955ca68dcb98393a00fb498a6efaa44ab55 | 0 | semonte/intellij-community,retomerz/intellij-community,semonte/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,diorcety/intellij-community,petteyg/intellij-community,signed/intellij-community,fnouama/intellij-community,diorcety/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,kool79/intellij-community,FHannes/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,petteyg/intellij-community,retomerz/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,holmes/intellij-community,samthor/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,caot/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,apixandru/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,signed/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ibinti/intellij-community,amith01994/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,da1z/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,slisson/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,da1z/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,petteyg/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,kool79/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,kdwink/intellij-community,izonder/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,slisson/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,vladmm/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,allotria/intellij-community,amith01994/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,caot/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,supersven/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,fitermay/intellij-community,adedayo/intellij-community,vladmm/intellij-community,signed/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,asedunov/intellij-community,semonte/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,izonder/intellij-community,signed/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,samthor/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,caot/intellij-community,signed/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,blademainer/intellij-community,supersven/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,holmes/intellij-community,ibinti/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,dslomov/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,allotria/intellij-community,apixandru/intellij-community,adedayo/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,semonte/intellij-community,caot/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,kool79/intellij-community,kool79/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,signed/intellij-community,adedayo/intellij-community,diorcety/intellij-community,izonder/intellij-community,amith01994/intellij-community,da1z/intellij-community,dslomov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ibinti/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,amith01994/intellij-community,allotria/intellij-community,jagguli/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,izonder/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,vladmm/intellij-community,slisson/intellij-community,caot/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,da1z/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,allotria/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,izonder/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,caot/intellij-community,slisson/intellij-community,allotria/intellij-community,slisson/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,retomerz/intellij-community,asedunov/intellij-community,amith01994/intellij-community,fitermay/intellij-community,izonder/intellij-community,hurricup/intellij-community,da1z/intellij-community,apixandru/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,izonder/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,FHannes/intellij-community,FHannes/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ryano144/intellij-community,ryano144/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,fitermay/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,da1z/intellij-community,kdwink/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,jagguli/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,caot/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,samthor/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,petteyg/intellij-community,supersven/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,amith01994/intellij-community,allotria/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,holmes/intellij-community,ryano144/intellij-community,retomerz/intellij-community,diorcety/intellij-community,supersven/intellij-community,dslomov/intellij-community,signed/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,ibinti/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,samthor/intellij-community,semonte/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,samthor/intellij-community,retomerz/intellij-community,signed/intellij-community,ryano144/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,caot/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,diorcety/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,slisson/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,allotria/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,semonte/intellij-community,xfournet/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,allotria/intellij-community,fitermay/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,Distrotech/intellij-community,holmes/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,da1z/intellij-community,adedayo/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,diorcety/intellij-community,izonder/intellij-community,vvv1559/intellij-community,kool79/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,caot/intellij-community,slisson/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,amith01994/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,clumsy/intellij-community,supersven/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,slisson/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,allotria/intellij-community,samthor/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.graph.linearBek;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.graph.actions.GraphAction;
import com.intellij.vcs.log.graph.api.GraphLayout;
import com.intellij.vcs.log.graph.api.LinearGraph;
import com.intellij.vcs.log.graph.api.elements.GraphEdge;
import com.intellij.vcs.log.graph.api.elements.GraphEdgeType;
import com.intellij.vcs.log.graph.api.elements.GraphElement;
import com.intellij.vcs.log.graph.api.elements.GraphNode;
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo;
import com.intellij.vcs.log.graph.impl.facade.BekBaseLinearGraphController;
import com.intellij.vcs.log.graph.impl.facade.CascadeLinearGraphController;
import com.intellij.vcs.log.graph.impl.facade.GraphChangesUtil;
import com.intellij.vcs.log.graph.impl.facade.bek.BekIntMap;
import com.intellij.vcs.log.graph.utils.LinearGraphUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class LinearBekController extends CascadeLinearGraphController {
private static final Logger LOG = Logger.getInstance(LinearBekController.class);
@NotNull private final LinearBekGraph myCompiledGraph;
private final LinearBekGraphBuilder myLinearBekGraphBuilder;
public LinearBekController(@NotNull BekBaseLinearGraphController controller, @NotNull PermanentGraphInfo permanentGraphInfo) {
super(controller, permanentGraphInfo);
myCompiledGraph = new LinearBekGraph(getDelegateLinearGraphController().getCompiledGraph());
myLinearBekGraphBuilder = new LinearBekGraphBuilder(myCompiledGraph, new BekGraphLayout(permanentGraphInfo.getPermanentGraphLayout(),
controller.getBekIntMap()));
long start = System.currentTimeMillis();
myLinearBekGraphBuilder.collapseAll();
LOG.info("Linear bek took " + (System.currentTimeMillis() - start) / 1000.0 + " sec");
}
@NotNull
@Override
protected LinearGraphAnswer delegateGraphChanged(@NotNull LinearGraphAnswer delegateAnswer) {
return delegateAnswer;
}
@Nullable
@Override
protected LinearGraphAnswer performAction(@NotNull LinearGraphAction action) {
if (action.getAffectedElement() != null) {
if (action.getType() == GraphAction.Type.MOUSE_CLICK) {
GraphElement graphElement = action.getAffectedElement().getGraphElement();
if (graphElement instanceof GraphEdge) {
GraphEdge edge = (GraphEdge)graphElement;
if (edge.getType() == GraphEdgeType.DOTTED) {
return new LinearGraphAnswer(GraphChangesUtil.edgesReplaced(Collections.singleton(edge), myCompiledGraph.expandEdge(edge),
getDelegateLinearGraphController().getCompiledGraph()), null, null,
null);
}
}
else if (graphElement instanceof GraphNode) {
if (myLinearBekGraphBuilder.collapseFragment(((GraphNode)graphElement).getNodeIndex())) {
return new LinearGraphAnswer(GraphChangesUtil.SOME_CHANGES, null, null, null);
}
}
}
else if (action.getType() == GraphAction.Type.MOUSE_OVER) {
GraphElement graphElement = action.getAffectedElement().getGraphElement();
if (graphElement instanceof GraphEdge) {
GraphEdge edge = (GraphEdge)graphElement;
if (edge.getType() == GraphEdgeType.DOTTED) {
return LinearGraphUtils
.createSelectedAnswer(myCompiledGraph, ContainerUtil.set(edge.getUpNodeIndex(), edge.getDownNodeIndex()));
}
}
else if (graphElement instanceof GraphNode) {
LinearBekGraphBuilder.MergeFragment fragment = myLinearBekGraphBuilder.getFragment(((GraphNode)graphElement).getNodeIndex());
if (fragment != null) {
return LinearGraphUtils.createSelectedAnswer(myCompiledGraph, fragment.getAllNodes());
}
}
}
}
else if (action.getType() == GraphAction.Type.BUTTON_COLLAPSE) {
return new LinearGraphAnswer(GraphChangesUtil.SOME_CHANGES, null, null, null) {
@Nullable
@Override
public Runnable getGraphUpdater() {
return new Runnable() {
@Override
public void run() {
myLinearBekGraphBuilder.collapseAll();
}
};
}
};
}
else if (action.getType() == GraphAction.Type.BUTTON_EXPAND) {
return new LinearGraphAnswer(GraphChangesUtil.SOME_CHANGES, null, null, null) {
@Nullable
@Override
public Runnable getGraphUpdater() {
return new Runnable() {
@Override
public void run() {
Set<GraphEdge> allEdges = myCompiledGraph.myDottedEdges.getEdges();
for (GraphEdge e : allEdges) {
if (myCompiledGraph.myDottedEdges.hasEdge(e.getUpNodeIndex(), e.getDownNodeIndex())) {
myCompiledGraph.expandEdge(e);
}
}
}
};
}
};
}
return null;
}
@NotNull
@Override
public LinearGraph getCompiledGraph() {
return myCompiledGraph;
}
private static class BekGraphLayout implements GraphLayout {
private final GraphLayout myGraphLayout;
private final BekIntMap myBekIntMap;
public BekGraphLayout(GraphLayout graphLayout, BekIntMap bekIntMap) {
myGraphLayout = graphLayout;
myBekIntMap = bekIntMap;
}
@Override
public int getLayoutIndex(int nodeIndex) {
return myGraphLayout.getLayoutIndex(myBekIntMap.getUsualIndex(nodeIndex));
}
@Override
public int getOneOfHeadNodeIndex(int nodeIndex) {
int usualIndex = myGraphLayout.getOneOfHeadNodeIndex(myBekIntMap.getUsualIndex(nodeIndex));
return myBekIntMap.getBekIndex(usualIndex);
}
@NotNull
@Override
public List<Integer> getHeadNodeIndex() {
List<Integer> bekIndexes = new ArrayList<Integer>();
for (int head : myGraphLayout.getHeadNodeIndex()) {
bekIndexes.add(myBekIntMap.getBekIndex(head));
}
return bekIndexes;
}
}
}
| platform/vcs-log/graph/src/com/intellij/vcs/log/graph/linearBek/LinearBekController.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.graph.linearBek;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.graph.actions.GraphAction;
import com.intellij.vcs.log.graph.api.GraphLayout;
import com.intellij.vcs.log.graph.api.LinearGraph;
import com.intellij.vcs.log.graph.api.elements.GraphEdge;
import com.intellij.vcs.log.graph.api.elements.GraphEdgeType;
import com.intellij.vcs.log.graph.api.elements.GraphElement;
import com.intellij.vcs.log.graph.api.elements.GraphNode;
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo;
import com.intellij.vcs.log.graph.impl.facade.BekBaseLinearGraphController;
import com.intellij.vcs.log.graph.impl.facade.CascadeLinearGraphController;
import com.intellij.vcs.log.graph.impl.facade.GraphChangesUtil;
import com.intellij.vcs.log.graph.impl.facade.bek.BekIntMap;
import com.intellij.vcs.log.graph.utils.LinearGraphUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class LinearBekController extends CascadeLinearGraphController {
private static final Logger LOG = Logger.getInstance(LinearBekController.class);
@NotNull private final LinearBekGraph myCompiledGraph;
private final LinearBekGraphBuilder myLinearBekGraphBuilder;
public LinearBekController(@NotNull BekBaseLinearGraphController controller, @NotNull PermanentGraphInfo permanentGraphInfo) {
super(controller, permanentGraphInfo);
myCompiledGraph = new LinearBekGraph(getDelegateLinearGraphController().getCompiledGraph());
myLinearBekGraphBuilder = new LinearBekGraphBuilder(myCompiledGraph, new BekGraphLayout(permanentGraphInfo.getPermanentGraphLayout(),
controller.getBekIntMap()));
long start = System.currentTimeMillis();
myLinearBekGraphBuilder.collapseAll();
LOG.info("Linear bek took " + (System.currentTimeMillis() - start) / 1000.0 + " sec");
}
@NotNull
@Override
protected LinearGraphAnswer delegateGraphChanged(@NotNull LinearGraphAnswer delegateAnswer) {
return delegateAnswer;
}
@Nullable
@Override
protected LinearGraphAnswer performAction(@NotNull LinearGraphAction action) {
if (action.getAffectedElement() != null) {
if (action.getType() == GraphAction.Type.MOUSE_CLICK) {
GraphElement graphElement = action.getAffectedElement().getGraphElement();
if (graphElement instanceof GraphEdge) {
GraphEdge edge = (GraphEdge)graphElement;
if (edge.getType() == GraphEdgeType.DOTTED) {
return new LinearGraphAnswer(GraphChangesUtil.edgesReplaced(Collections.singleton(edge), myCompiledGraph.expandEdge(edge),
getDelegateLinearGraphController().getCompiledGraph()), null, null, null);
}
}
else if (graphElement instanceof GraphNode) {
if (myLinearBekGraphBuilder.collapseFragment(((GraphNode)graphElement).getNodeIndex())) {
return new LinearGraphAnswer(GraphChangesUtil.SOME_CHANGES, null, null, null);
}
}
}
else if (action.getType() == GraphAction.Type.MOUSE_OVER) {
GraphElement graphElement = action.getAffectedElement().getGraphElement();
if (graphElement instanceof GraphEdge) {
GraphEdge edge = (GraphEdge)graphElement;
if (edge.getType() == GraphEdgeType.DOTTED) {
return LinearGraphUtils
.createSelectedAnswer(myCompiledGraph, ContainerUtil.set(edge.getUpNodeIndex(), edge.getDownNodeIndex()));
}
}
else if (graphElement instanceof GraphNode) {
LinearBekGraphBuilder.MergeFragment fragment = myLinearBekGraphBuilder.getFragment(((GraphNode)graphElement).getNodeIndex());
if (fragment != null) {
return LinearGraphUtils.createSelectedAnswer(myCompiledGraph, fragment.getAllNodes());
}
}
}
}
return null;
}
@NotNull
@Override
public LinearGraph getCompiledGraph() {
return myCompiledGraph;
}
private static class BekGraphLayout implements GraphLayout {
private final GraphLayout myGraphLayout;
private final BekIntMap myBekIntMap;
public BekGraphLayout(GraphLayout graphLayout, BekIntMap bekIntMap) {
myGraphLayout = graphLayout;
myBekIntMap = bekIntMap;
}
@Override
public int getLayoutIndex(int nodeIndex) {
return myGraphLayout.getLayoutIndex(myBekIntMap.getUsualIndex(nodeIndex));
}
@Override
public int getOneOfHeadNodeIndex(int nodeIndex) {
int usualIndex = myGraphLayout.getOneOfHeadNodeIndex(myBekIntMap.getUsualIndex(nodeIndex));
return myBekIntMap.getBekIndex(usualIndex);
}
@NotNull
@Override
public List<Integer> getHeadNodeIndex() {
List<Integer> bekIndexes = new ArrayList<Integer>();
for (int head : myGraphLayout.getHeadNodeIndex()) {
bekIndexes.add(myBekIntMap.getBekIndex(head));
}
return bekIndexes;
}
}
}
| [vcs-log] new meaning to collapse and expand buttons in linear bek graph
| platform/vcs-log/graph/src/com/intellij/vcs/log/graph/linearBek/LinearBekController.java | [vcs-log] new meaning to collapse and expand buttons in linear bek graph | <ide><path>latform/vcs-log/graph/src/com/intellij/vcs/log/graph/linearBek/LinearBekController.java
<ide> import org.jetbrains.annotations.NotNull;
<ide> import org.jetbrains.annotations.Nullable;
<ide>
<del>import java.util.*;
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.List;
<add>import java.util.Set;
<ide>
<ide> public class LinearBekController extends CascadeLinearGraphController {
<ide> private static final Logger LOG = Logger.getInstance(LinearBekController.class);
<ide> GraphEdge edge = (GraphEdge)graphElement;
<ide> if (edge.getType() == GraphEdgeType.DOTTED) {
<ide> return new LinearGraphAnswer(GraphChangesUtil.edgesReplaced(Collections.singleton(edge), myCompiledGraph.expandEdge(edge),
<del> getDelegateLinearGraphController().getCompiledGraph()), null, null, null);
<add> getDelegateLinearGraphController().getCompiledGraph()), null, null,
<add> null);
<ide> }
<ide> }
<ide> else if (graphElement instanceof GraphNode) {
<ide> }
<ide> }
<ide> }
<add> }
<add> else if (action.getType() == GraphAction.Type.BUTTON_COLLAPSE) {
<add> return new LinearGraphAnswer(GraphChangesUtil.SOME_CHANGES, null, null, null) {
<add> @Nullable
<add> @Override
<add> public Runnable getGraphUpdater() {
<add> return new Runnable() {
<add> @Override
<add> public void run() {
<add> myLinearBekGraphBuilder.collapseAll();
<add> }
<add> };
<add> }
<add> };
<add> }
<add> else if (action.getType() == GraphAction.Type.BUTTON_EXPAND) {
<add> return new LinearGraphAnswer(GraphChangesUtil.SOME_CHANGES, null, null, null) {
<add> @Nullable
<add> @Override
<add> public Runnable getGraphUpdater() {
<add> return new Runnable() {
<add> @Override
<add> public void run() {
<add> Set<GraphEdge> allEdges = myCompiledGraph.myDottedEdges.getEdges();
<add> for (GraphEdge e : allEdges) {
<add> if (myCompiledGraph.myDottedEdges.hasEdge(e.getUpNodeIndex(), e.getDownNodeIndex())) {
<add> myCompiledGraph.expandEdge(e);
<add> }
<add> }
<add> }
<add> };
<add> }
<add> };
<ide> }
<ide> return null;
<ide> } |
|
Java | agpl-3.0 | c9b161142c8454e83ea615375d84738143762cbc | 0 | akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow | package org.waterforpeople.mapping.app.web;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.datanucleus.store.appengine.query.JDOCursorHelper;
import org.waterforpeople.mapping.analytics.MapSummarizer;
import org.waterforpeople.mapping.analytics.dao.AccessPointStatusSummaryDao;
import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary;
import org.waterforpeople.mapping.app.gwt.client.device.DeviceDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyAssignmentDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType;
import org.waterforpeople.mapping.app.gwt.server.accesspoint.AccessPointManagerServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.devicefiles.DeviceFilesServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.survey.SurveyAssignmentServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.survey.SurveyServiceImpl;
import org.waterforpeople.mapping.dao.AccessPointDao;
import org.waterforpeople.mapping.dao.CommunityDao;
import org.waterforpeople.mapping.dao.DeviceFilesDao;
import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao;
import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao;
import org.waterforpeople.mapping.dao.SurveyContainerDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.dataexport.DeviceFilesReplicationImporter;
import org.waterforpeople.mapping.dataexport.SurveyReplicationImporter;
import org.waterforpeople.mapping.domain.AccessPoint;
import org.waterforpeople.mapping.domain.Community;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.SurveyAssignment;
import org.waterforpeople.mapping.domain.SurveyAttributeMapping;
import org.waterforpeople.mapping.domain.SurveyInstance;
import org.waterforpeople.mapping.domain.TechnologyType;
import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType;
import org.waterforpeople.mapping.domain.AccessPoint.Status;
import org.waterforpeople.mapping.domain.Status.StatusCode;
import org.waterforpeople.mapping.helper.AccessPointHelper;
import org.waterforpeople.mapping.helper.GeoRegionHelper;
import org.waterforpeople.mapping.helper.KMLHelper;
import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.gallatinsystems.common.util.ZipUtil;
import com.gallatinsystems.device.dao.DeviceDAO;
import com.gallatinsystems.device.domain.Device;
import com.gallatinsystems.device.domain.DeviceFiles;
import com.gallatinsystems.device.domain.DeviceSurveyJobQueue;
import com.gallatinsystems.device.domain.Device.DeviceType;
import com.gallatinsystems.diagnostics.dao.RemoteStacktraceDao;
import com.gallatinsystems.diagnostics.domain.RemoteStacktrace;
import com.gallatinsystems.editorial.dao.EditorialPageDao;
import com.gallatinsystems.editorial.domain.EditorialPage;
import com.gallatinsystems.editorial.domain.EditorialPageContent;
import com.gallatinsystems.editorial.domain.MapBalloonDefinition;
import com.gallatinsystems.editorial.domain.MapBalloonDefinition.BalloonType;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.framework.domain.BaseDomain;
import com.gallatinsystems.framework.exceptions.IllegalDeletionException;
import com.gallatinsystems.gis.geography.domain.Country;
import com.gallatinsystems.gis.location.GeoLocationServiceGeonamesImpl;
import com.gallatinsystems.gis.location.GeoPlace;
import com.gallatinsystems.gis.map.dao.MapFragmentDao;
import com.gallatinsystems.gis.map.dao.OGRFeatureDao;
import com.gallatinsystems.gis.map.domain.Geometry;
import com.gallatinsystems.gis.map.domain.MapFragment;
import com.gallatinsystems.gis.map.domain.OGRFeature;
import com.gallatinsystems.gis.map.domain.Geometry.GeometryType;
import com.gallatinsystems.gis.map.domain.MapFragment.FRAGMENTTYPE;
import com.gallatinsystems.notification.NotificationRequest;
import com.gallatinsystems.notification.helper.NotificationHelper;
import com.gallatinsystems.survey.dao.DeviceSurveyJobQueueDAO;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.QuestionHelpMediaDao;
import com.gallatinsystems.survey.dao.QuestionOptionDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyGroupDAO;
import com.gallatinsystems.survey.dao.SurveyTaskUtil;
import com.gallatinsystems.survey.dao.TranslationDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionHelpMedia;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyContainer;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.gallatinsystems.survey.domain.SurveyXMLFragment;
import com.gallatinsystems.survey.domain.Translation;
import com.gallatinsystems.survey.domain.Question.Type;
import com.gallatinsystems.survey.domain.Translation.ParentType;
import com.gallatinsystems.user.dao.UserDao;
import com.gallatinsystems.user.domain.Permission;
import com.gallatinsystems.user.domain.User;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
public class TestHarnessServlet extends HttpServlet {
private static Logger log = Logger.getLogger(TestHarnessServlet.class
.getName());
private static final long serialVersionUID = -5673118002247715049L;
@SuppressWarnings("unused")
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String action = req.getParameter("action");
if ("testSurveyOrdering".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
SurveyGroup sgItem = sgDao.list("all").get(0);
sgItem = sgDao.getByKey(sgItem.getKey().getId(), true);
} else if ("setupTestUser".equals(action)) {
setupTestUser();
} else if ("reorderQuestionsByCollectionDate".equals(action)) {
try {
Long surveyId = Long.parseLong(req.getParameter("surveyId"));
SurveyDAO surveyDao = new SurveyDAO();
QuestionDao qDao = new QuestionDao();
Survey survey = surveyDao.loadFullSurvey(surveyId);
int i = 0;
for (Map.Entry<Integer, QuestionGroup> qGEntry : survey
.getQuestionGroupMap().entrySet()) {
List<Question> qList = qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
.getValue().getKey().getId());
for (Question q : qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
.getValue().getKey().getId())) {
q.setOrder(i + 1);
qDao.save(q);
resp.getWriter().println(
q.getOrder() + " :Change: " + q.getText());
++i;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("genBalloonData".equals(action)) {
MapBalloonDefinition mpd = new MapBalloonDefinition();
mpd.setBalloonType(BalloonType.KML_WATER_POINT);
mpd.setStyleData("@charset \"utf-8\"; body {font-family: Trebuchet MS, Arial, Helvetica, sans-serif;font-weight: bold;color: #6d6e71;}");
mpd.setName("WFPWaterPoint");
} else if ("deleteGeoData".equals(action)) {
try {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
for (OGRFeature item : ogrFeatureDao.list("all")) {
resp.getWriter().println(
"deleting: " + item.getCountryCode());
ogrFeatureDao.delete(item);
}
resp.getWriter().println("Finished");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testGeoLocation".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
String lat = req.getParameter("lat");
String lon = req.getParameter("lon");
GeoPlace geoPlace = gs.manualLookup(lat, lon);
try {
if (geoPlace != null)
resp.getWriter().println(
"Found: " + geoPlace.getCountryName() + ":"
+ geoPlace.getCountryCode() + " for " + lat
+ ", " + lon);
geoPlace = gs.manualLookup(lat, lon,
OGRFeature.FeatureType.SUB_COUNTRY_OTHER);
if (geoPlace != null)
resp.getWriter().println(
"Found: " + geoPlace.getCountryCode() + ":"
+ geoPlace.getSub1() + ":"
+ geoPlace.getSub2() + ":"
+ geoPlace.getSub3() + ":"
+ geoPlace.getSub4() + ":"
+ geoPlace.getSub5() + ":"
+ geoPlace.getSub6() + " for " + lat + ", "
+ lon);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("RemapAPToSub".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
} else if ("loadOGRFeature".equals(action)) {
OGRFeature ogrFeature = new OGRFeature();
ogrFeature.setName("clan-21061011");
ogrFeature.setProjectCoordinateSystemIdentifier("World_Mercator");
ogrFeature.setGeoCoordinateSystemIdentifier("GCS_WGS_1984");
ogrFeature.setDatumIdentifier("WGS_1984");
ogrFeature.setSpheroid(6378137D);
ogrFeature.setReciprocalOfFlattening(298.257223563);
ogrFeature.setCountryCode("LR");
ogrFeature.addBoundingBox(223700.015625, 481399.468750,
680781.375000, 945462.437500);
Geometry geo = new Geometry();
geo.setType(GeometryType.POLYGON);
String coords = "497974.5625 557051.875,498219.03125 557141.75,498655.34375 557169.4375,499001.65625 557100.1875,499250.96875 556933.9375,499167.875 556615.375,499230.1875 556407.625,499392.78125 556362.75,499385.90625 556279.875,499598.5 556067.3125,499680.25 555952.8125,499218.5625 554988.875,498775.65625 554860.1875,498674.5 554832.5625,498282.0 554734.4375,498020.34375 554554.5625,497709.59375 554374.6875,497614.84375 554374.6875,497519.46875 554369.1875,497297.3125 554359.9375,496852.96875 554355.3125,496621.125 554351.375,496695.75 554454.625,496771.59375 554604.625,496836.3125 554734.0625,496868.65625 554831.125,496847.09375 554863.4375,496760.8125 554863.4375,496663.75 554928.125,496620.625 554992.875,496555.90625 555025.1875,496448.0625 554992.875,496372.5625 555025.1875,496351.0 555133.0625,496415.71875 555197.75,496480.40625 555294.8125,496480.40625 555381.0625,496430.875 555430.75,496446.0625 555547.375,496490.53125 555849.625,496526.09375 556240.75,496721.65625 556596.375,496924.90625 556774.1875,497006.125 556845.25,497281.71875 556978.625,497610.625 556969.6875,497859.53125 556969.6875,497974.5625 557051.875";
for (String item : coords.split(",")) {
String[] coord = item.split(" ");
geo.addCoordinate(Double.parseDouble(coord[0]),
Double.parseDouble(coord[1]));
}
ogrFeature.setGeometry(geo);
ogrFeature.addGeoMeasure("CLNAME", "STRING", "Loisiana Township");
ogrFeature.addGeoMeasure("COUNT", "FLOAT", "1");
BaseDAO<OGRFeature> ogrDao = new BaseDAO<OGRFeature>(
OGRFeature.class);
ogrDao.save(ogrFeature);
try {
resp.getWriter()
.println("OGRFeature: " + ogrFeature.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("resetLRAP".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
Random rand = new Random();
for (AccessPoint ap : apDao.list("all")) {
if ((ap.getCountryCode() == null || ap.getCountryCode()
.equals("US"))
&& (ap.getLatitude() != null && ap.getLongitude() != null)) {
if (ap.getLatitude() > 5.0 && ap.getLatitude() < 11) {
if (ap.getLongitude() < -9
&& ap.getLongitude() > -11) {
ap.setCountryCode("LR");
apDao.save(ap);
resp.getWriter()
.println(
"Found "
+ ap.getCommunityCode()
+ "mapped to US changing mapping to LR \n");
}
}
} else if (ap.getCommunityCode() == null) {
ap.setCommunityCode(rand.nextLong() + "");
apDao.save(ap);
resp.getWriter().println(
"Found " + ap.getCommunityCode()
+ "added random community code \n");
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("clearSurveyInstanceQAS".equals(action)) {
// QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
// for (QuestionAnswerStore qas : qasDao.list("all")) {
// qasDao.delete(qas);
// }
// SurveyInstanceDAO siDao = new SurveyInstanceDAO();
// for (SurveyInstance si : siDao.list("all")) {
// siDao.delete(si);
// }
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all"))
apDao.delete(ap);
} else if ("SurveyInstance".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
List<SurveyInstance> siList = siDao.listSurveyInstanceBySurveyId(
1362011L, null);
Cursor cursor = JDOCursorHelper.getCursor(siList);
int i = 0;
while (siList.size() > 0) {
for (SurveyInstance si : siList) {
System.out.println(i++ + " " + si.toString());
String surveyInstanceId = new Long(si.getKey().getId())
.toString();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(url("/app_worker/surveytask").param("action",
"reprocessMapSurveyInstance").param("id",
surveyInstanceId));
log.info("submiting task for SurveyInstanceId: "
+ surveyInstanceId);
}
siList = siDao.listSurveyInstanceBySurveyId(1362011L,
cursor.toWebSafeString());
cursor = JDOCursorHelper.getCursor(siList);
}
System.out.println("finished");
} else if ("rotateImage".equals(action)) {
AccessPointManagerServiceImpl apmI = new AccessPointManagerServiceImpl();
String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg";
// String test2 =
// "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg";
writeImageToResponse(resp, test1);
apmI.setUploadS3Flag(false);
writeImageToResponse(resp, apmI.rotateImage(test1));
// apmI.rotateImage(test2);
} else if ("clearSurveyGroupGraph".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.delete(sgDao.list("all"));
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.delete(surveyDao.list("all"));
QuestionGroupDao qgDao = new QuestionGroupDao();
qgDao.delete(qgDao.list("all"));
QuestionDao qDao = new QuestionDao();
qDao.delete(qDao.list("all"));
QuestionHelpMediaDao qhDao = new QuestionHelpMediaDao();
qhDao.delete(qhDao.list("all"));
QuestionOptionDao qoDao = new QuestionOptionDao();
qoDao.delete(qoDao.list("all"));
TranslationDao tDao = new TranslationDao();
tDao.delete(tDao.list("all"));
/*
* createSurveyGroupGraph(resp); //SurveyGroupDAO sgDao = new
* SurveyGroupDAO(); List<SurveyGroup> sgList = sgDao.list("all");
* Survey survey = sgList.get(0).getSurveyList().get(0);
* QuestionAnswerStore qas = new QuestionAnswerStore();
* qas.setArbitratyNumber(1L);
* qas.setSurveyId(survey.getKey().getId()); qas.setQuestionID("1");
* qas.setValue("test"); QuestionAnswerStoreDao qasDao = new
* QuestionAnswerStoreDao(); qasDao.save(qas);
*
*
* for(SurveyGroup sg: sgList) sgDao.delete(sg);
*/
} else if ("replicateDeviceFiles".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
for (SurveyInstance si : siDao.list("all")) {
siDao.delete(si);
}
QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
for (QuestionAnswerStore qas : qasDao.list("all")) {
qasDao.delete(qas);
}
DeviceFilesDao dfDao = new DeviceFilesDao();
for (DeviceFiles df : dfDao.list("all")) {
dfDao.delete(df);
}
DeviceFilesReplicationImporter dfri = new DeviceFilesReplicationImporter();
dfri.executeImport("http://watermapmonitordev.appspot.com",
"http://localhost:8888");
Set<String> dfSet = new HashSet<String>();
for (DeviceFiles df : dfDao.list("all")) {
dfSet.add(df.getURI());
}
DeviceFilesServiceImpl dfsi = new DeviceFilesServiceImpl();
int i = 0;
try {
resp.getWriter().println(
"Found " + dfSet.size() + " distinct files to process");
for (String s : dfSet) {
dfsi.reprocessDeviceFile(s);
resp.getWriter().println(
"submitted " + s + " for reprocessing");
i++;
if (i > 10)
break;
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("addDeviceFiles".equals(action)) {
DeviceFilesDao dfDao = new DeviceFilesDao();
DeviceFiles df = new DeviceFiles();
df.setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip");
df.setCreatedDateTime(new Date());
df.setPhoneNumber("a4:ed:4e:54:ef:6d");
df.setChecksum("1149406886");
df.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP);
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
java.util.Date date = new java.util.Date();
String dateTime = dateFormat.format(date);
df.setProcessDate(dateTime);
dfDao.save(df);
} else if ("testBaseDomain".equals(action)) {
SurveyDAO surveyDAO = new SurveyDAO();
String outString = surveyDAO.getForTest();
BaseDAO<AccessPoint> pointDao = new BaseDAO<AccessPoint>(
AccessPoint.class);
AccessPoint point = new AccessPoint();
point.setLatitude(78d);
point.setLongitude(43d);
pointDao.save(point);
try {
resp.getWriter().print(outString);
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("testSaveRegion".equals(action)) {
GeoRegionHelper geoHelp = new GeoRegionHelper();
ArrayList<String> regionLines = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
StringBuilder builder = new StringBuilder();
builder.append("1,").append("" + i).append(",test,")
.append(20 + i + ",").append(30 + i + "\n");
regionLines.add(builder.toString());
}
geoHelp.processRegionsSurvey(regionLines);
try {
resp.getWriter().print("Save complete");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save test region", e);
}
} else if ("clearAccessPoint".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all")) {
apDao.delete(ap);
try {
resp.getWriter().print(
"Finished Deleting AP: " + ap.toString());
} catch (IOException e) {
log.log(Level.SEVERE, "Could not delete ap");
}
}
resp.getWriter().print("Deleted AccessPoints complete");
BaseDAO<AccessPointStatusSummary> apsDao = new BaseDAO<AccessPointStatusSummary>(
AccessPointStatusSummary.class);
for (AccessPointStatusSummary item : apsDao.list("all")) {
apsDao.delete(item);
}
resp.getWriter().print("Deleted AccessPointStatusSummary");
MapFragmentDao mfDao = new MapFragmentDao();
for (MapFragment item : mfDao.list("all")) {
mfDao.delete(item);
}
resp.getWriter().print("Cleared MapFragment Table");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not clear AP and APStatusSummary",
e);
}
} else if ("loadErrorPoints".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
AccessPointDao apDao = new AccessPointDao();
for (int j = 0; j < 1; j++) {
Double lat = 0.0;
Double lon = 0.0;
for (int i = 0; i < 5; i++) {
AccessPoint ap = new AccessPoint();
ap.setLatitude(lat);
ap.setLongitude(lon);
Calendar calendar = Calendar.getInstance();
Date today = new Date();
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1 * i);
System.out
.println("AP: " + ap.getLatitude() + "/"
+ ap.getLongitude() + "Date: "
+ calendar.getTime());
ap.setCollectionDate(calendar.getTime());
ap.setAltitude(0.0);
ap.setCommunityCode("test" + new Date());
ap.setCommunityName("test" + new Date());
ap.setPhotoURL("http://test.com");
ap.setPointType(AccessPoint.AccessPointType.WATER_POINT);
if (i == 0)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
else if (i == 1)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK);
else if (i == 2)
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
else
ap.setPointStatus(Status.NO_IMPROVED_SYSTEM);
if (i % 2 == 0)
ap.setTypeTechnologyString("Kiosk");
else
ap.setTypeTechnologyString("Afridev Handpump");
apDao.save(ap);
MapSummarizer ms = new MapSummarizer();
// ms.performSummarization("" + ap.getKey().getId(), "");
if (i % 50 == 0)
log.log(Level.INFO, "Loaded to " + i);
}
}
try {
resp.getWriter().println("Finished loading aps");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("loadLots".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
AccessPointDao apDao = new AccessPointDao();
for (int j = 0; j < 1; j++) {
double lat = -15 + (new Random().nextDouble() / 10);
double lon = 35 + (new Random().nextDouble() / 10);
for (int i = 0; i < 3000; i++) {
AccessPoint ap = new AccessPoint();
ap.setLatitude(lat);
ap.setLongitude(lon);
Calendar calendar = Calendar.getInstance();
Date today = new Date();
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1 * i);
System.out
.println("AP: " + ap.getLatitude() + "/"
+ ap.getLongitude() + "Date: "
+ calendar.getTime());
// ap.setCollectionDate(calendar.getTime());
ap.setAltitude(0.0);
ap.setCommunityCode("test" + new Date());
ap.setCommunityName("test" + new Date());
ap.setPhotoURL("http://waterforpeople.s3.amazonaws.com/images/peru/pc28water.jpg");
ap.setProvideAdequateQuantity(true);
ap.setHasSystemBeenDown1DayFlag(false);
ap.setMeetGovtQualityStandardFlag(true);
ap.setMeetGovtQuantityStandardFlag(false);
ap.setCurrentManagementStructurePoint("Community Board");
ap.setDescription("Waterpoint");
ap.setDistrict("test district");
ap.setEstimatedHouseholds(100L);
ap.setEstimatedPeoplePerHouse(11L);
ap.setFarthestHouseholdfromPoint("Yes");
ap.setNumberOfHouseholdsUsingPoint(100L);
ap.setConstructionDateYear("2001");
ap.setCostPer(1.0);
ap.setCountryCode("MW");
ap.setConstructionDate(new Date());
ap.setCollectionDate(new Date());
ap.setPhotoName("Water point");
if (i % 2 == 0)
ap.setPointType(AccessPoint.AccessPointType.WATER_POINT);
else if (i % 3 == 0)
ap.setPointType(AccessPoint.AccessPointType.SANITATION_POINT);
else
ap.setPointType(AccessPoint.AccessPointType.PUBLIC_INSTITUTION);
if (i == 0)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
else if (i == 1)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK);
else if (i == 2)
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
else
ap.setPointStatus(Status.NO_IMPROVED_SYSTEM);
if (i % 2 == 0)
ap.setTypeTechnologyString("Kiosk");
else
ap.setTypeTechnologyString("Afridev Handpump");
apDao.save(ap);
MapSummarizer ms = new MapSummarizer();
// ms.performSummarization("" + ap.getKey().getId(), "");
if (i % 50 == 0)
log.log(Level.INFO, "Loaded to " + i);
}
}
try {
resp.getWriter().println("Finished loading aps");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("loadCountries".equals(action)) {
Country c = new Country();
c.setIsoAlpha2Code("HN");
c.setName("Honduras");
BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class);
countryDAO.save(c);
Country c2 = new Country();
c2.setIsoAlpha2Code("MW");
c2.setName("Malawi");
countryDAO.save(c2);
} else if ("testAPKml".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
BaseDAO<TechnologyType> ttDao = new BaseDAO<TechnologyType>(
TechnologyType.class);
List<TechnologyType> ttList = ttDao.list("all");
for (TechnologyType tt : ttList)
ttDao.delete(tt);
TechnologyType tt = new TechnologyType();
tt.setCode("Afridev Handpump");
tt.setName("Afridev Handpump");
ttDao.save(tt);
TechnologyType tt2 = new TechnologyType();
tt2.setCode("Kiosk");
tt2.setName("Kiosk");
ttDao.save(tt2);
KMLHelper kmlHelper = new KMLHelper();
kmlHelper.buildMap();
List<MapFragment> mfList = mfDao.searchMapFragments("ALL", null,
null, null, FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all",
null, null);
try {
for (MapFragment mfItem : mfList) {
String contents = ZipUtil
.unZip(mfItem.getBlob().getBytes());
log.log(Level.INFO, "Contents Length: " + contents.length());
resp.setContentType("application/vnd.google-earth.kmz+xml");
ServletOutputStream out = resp.getOutputStream();
resp.setHeader("Content-Disposition",
"inline; filename=waterforpeoplemapping.kmz;");
out.write(mfItem.getBlob().getBytes());
out.flush();
}
} catch (IOException ie) {
log.log(Level.SEVERE, "Could not list fragment");
}
} else if ("deleteSurveyGraph".equals(action)) {
deleteAll(SurveyGroup.class);
deleteAll(Survey.class);
deleteAll(QuestionGroup.class);
deleteAll(Question.class);
deleteAll(Translation.class);
deleteAll(QuestionOption.class);
deleteAll(QuestionHelpMedia.class);
try {
resp.getWriter().println("Finished deleting survey graph");
} catch (IOException iex) {
log.log(Level.SEVERE, "couldn't delete surveyGraph" + iex);
}
}
else if ("saveSurveyGroupRefactor".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
createSurveyGroupGraph(resp);
try {
List<SurveyGroup> savedSurveyGroups = sgDao.list("all");
for (SurveyGroup sgItem : savedSurveyGroups) {
resp.getWriter().println("SG: " + sgItem.getCode());
for (Survey survey : sgItem.getSurveyList()) {
resp.getWriter().println(
" Survey:" + survey.getName());
for (Map.Entry<Integer, QuestionGroup> entry : survey
.getQuestionGroupMap().entrySet()) {
resp.getWriter().println(
" QuestionGroup: " + entry.getKey()
+ ":" + entry.getValue().getDesc());
for (Map.Entry<Integer, Question> questionEntry : entry
.getValue().getQuestionMap().entrySet()) {
resp.getWriter().println(
" Question"
+ questionEntry.getKey()
+ ":"
+ questionEntry.getValue()
.getText());
for (Map.Entry<Integer, QuestionHelpMedia> qhmEntry : questionEntry
.getValue().getQuestionHelpMediaMap()
.entrySet()) {
resp.getWriter().println(
" QuestionHelpMedia"
+ qhmEntry.getKey()
+ ":"
+ qhmEntry.getValue()
.getText());
/*
* for (Key tKey : qhmEntry.getValue()
* .getAltTextKeyList()) { Translation t =
* tDao.getByKey(tKey);
* resp.getWriter().println(
* " QHMAltText" +
* t.getLanguageCode() + ":" + t.getText());
* }
*/
}
}
}
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save sg");
}
} else if ("createAP".equals(action)) {
AccessPoint ap = new AccessPoint();
ap.setCollectionDate(new Date());
ap.setCommunityCode(new Random().toString());
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setCountryCode("SZ");
ap.setPointType(AccessPointType.WATER_POINT);
AccessPointHelper helper = new AccessPointHelper();
helper.saveAccessPoint(ap);
} else if ("createInstance".equals(action)) {
SurveyInstance si = new SurveyInstance();
si.setCollectionDate(new Date());
ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>();
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID("q2");
ans.setValue("Geneva");
store.add(ans);
si.setQuestionAnswersStore(store);
SurveyInstanceDAO dao = new SurveyInstanceDAO();
si = dao.save(si);
Queue summQueue = QueueFactory.getQueue("dataSummarization");
summQueue.add(url("/app_worker/datasummarization").param(
"objectKey", si.getKey().getId() + "").param("type",
"SurveyInstance"));
} else if ("createCommunity".equals(action)) {
CommunityDao dao = new CommunityDao();
Country c = new Country();
c.setIsoAlpha2Code("CA");
c.setName("Canada");
c.setDisplayName("Canada");
Community comm = new Community();
comm.setCommunityCode("ON");
dao.save(c);
comm.setCountryCode("CA");
comm.setLat(54.99);
comm.setLon(-74.72);
dao.save(comm);
c = new Country();
c.setIsoAlpha2Code("US");
c.setName("United States");
c.setDisplayName("Unites States");
comm = new Community();
comm.setCommunityCode("Omaha");
comm.setCountryCode("US");
comm.setLat(34.99);
comm.setLon(-74.72);
dao.save(c);
dao.save(comm);
} else if ("addPhone".equals(action)) {
String phoneNumber = req.getParameter("phoneNumber");
Device d = new Device();
d.setPhoneNumber(phoneNumber);
d.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
if (req.getParameter("esn") != null)
d.setEsn(req.getParameter("esn"));
if (req.getParameter("gallatinSoftwareManifest") != null)
d.setGallatinSoftwareManifest(req
.getParameter("gallatinSoftwareManifest"));
d.setInServiceDate(new Date());
DeviceDAO deviceDao = new DeviceDAO();
deviceDao.save(d);
try {
resp.getWriter().println("finished adding " + phoneNumber);
} catch (Exception e) {
e.printStackTrace();
}
} else if ("createAPSummary".equals(action)) {
AccessPointStatusSummary sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao();
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
} else if ("createApHistory".equals(action)) {
GregorianCalendar cal = new GregorianCalendar();
AccessPointHelper apHelper = new AccessPointHelper();
AccessPoint ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(300l);
ap.setCostPer(43.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(317l);
ap.setCostPer(40.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(37.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(34.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(338l);
ap.setCostPer(38.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(170l);
ap.setCostPer(19.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(201l);
ap.setCostPer(19.00);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(211l);
ap.setCostPer(17.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(220l);
ap.setCostPer(25.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(175l);
ap.setCostPer(24.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
} else if ("generateGeocells".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
List<AccessPoint> apList = apDao.list(null);
if (apList != null) {
for (AccessPoint ap : apList) {
if (ap.getGeocells() == null
|| ap.getGeocells().size() == 0) {
if (ap.getLatitude() != null
&& ap.getLongitude() != null) {
ap.setGeocells(GeocellManager.generateGeoCell(new Point(
ap.getLatitude(), ap.getLongitude())));
apDao.save(ap);
}
}
}
}
} else if ("loadExistingSurvey".equals(action)) {
SurveyGroup sg = new SurveyGroup();
sg.setKey(KeyFactory.createKey(SurveyGroup.class.getSimpleName(),
2L));
sg.setName("test" + new Date());
sg.setCode("test" + new Date());
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.save(sg);
Survey s = new Survey();
s.setKey(KeyFactory.createKey(Survey.class.getSimpleName(), 2L));
s.setName("test" + new Date());
s.setSurveyGroupId(sg.getKey().getId());
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.save(s);
} else if ("saveAPMapping".equals(action)) {
SurveyAttributeMapping mapping = new SurveyAttributeMapping();
mapping.setAttributeName("status");
mapping.setObjectName(AccessPoint.class.getCanonicalName());
mapping.setSurveyId(1L);
mapping.setSurveyQuestionId("q1");
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
samDao.save(mapping);
} else if ("listAPMapping".equals(action)) {
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
List<SurveyAttributeMapping> mappings = samDao
.listMappingsBySurvey(1L);
if (mappings != null) {
System.out.println(mappings.size());
}
} else if ("saveSurveyGroup".equals(action)) {
try {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
List<SurveyGroup> sgList = sgDao.list("all");
for (SurveyGroup sg : sgList) {
sgDao.delete(sg);
}
resp.getWriter().println("Deleted all survey groups");
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey survey : surveyList) {
try {
surveyDao.delete(survey);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all surveys");
resp.getWriter().println("Deleted all surveysurveygroupassocs");
QuestionGroupDao qgDao = new QuestionGroupDao();
List<QuestionGroup> qgList = qgDao.list("all");
for (QuestionGroup qg : qgList) {
qgDao.delete(qg);
}
resp.getWriter().println("Deleted all question groups");
QuestionDao qDao = new QuestionDao();
List<Question> qList = qDao.list("all");
for (Question q : qList) {
try {
qDao.delete(q);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all Questions");
QuestionOptionDao qoDao = new QuestionOptionDao();
List<QuestionOption> qoList = qoDao.list("all");
for (QuestionOption qo : qoList)
qoDao.delete(qo);
resp.getWriter().println("Deleted all QuestionOptions");
resp.getWriter().println("Deleted all questions");
resp.getWriter().println(
"Finished deleting and reloading SurveyGroup graph");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("testPublishSurvey".equals(action)) {
try {
SurveyGroupDto sgDto = new SurveyServiceImpl()
.listSurveyGroups(null, true, false, false).get(0);
resp.getWriter().println(
"Got Survey Group: " + sgDto.getCode() + " Survey: "
+ sgDto.getSurveyList().get(0).getKeyId());
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(sgDto.getSurveyList()
.get(0).getKeyId());
if (sc != null) {
scDao.delete(sc);
resp.getWriter().println(
"Deleted existing SurveyContainer for: "
+ sgDto.getSurveyList().get(0).getKeyId());
}
resp.getWriter().println(
"Result of publishing survey: "
+ new SurveyServiceImpl().publishSurvey(sgDto
.getSurveyList().get(0).getKeyId()));
sc = scDao.findBySurveyId(sgDto.getSurveyList().get(0)
.getKeyId());
resp.getWriter().println(
"Survey Document result from publish: \n\n\n\n"
+ sc.getSurveyDocument().getValue());
} catch (IOException ex) {
ex.printStackTrace();
}
} else if ("createTestSurveyForEndToEnd".equals(action)) {
createTestSurveyForEndToEnd();
} else if ("deleteSurveyFragments".equals(action)) {
deleteAll(SurveyXMLFragment.class);
} else if ("migratePIToSchool".equals(action)) {
try {
resp.getWriter().println(
"Has more? "
+ migratePointType(
AccessPointType.PUBLIC_INSTITUTION,
AccessPointType.SCHOOL));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("createDevice".equals(action)) {
DeviceDAO devDao = new DeviceDAO();
Device device = new Device();
device.setPhoneNumber("9175667663");
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
devDao.save(device);
} else if ("reprocessSurveys".equals(action)) {
try {
reprocessSurveys(req.getParameter("date"));
} catch (ParseException e) {
try {
resp.getWriter().println("Couldn't reprocess: " + e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else if ("importallsurveys".equals(action)) {
// Only run in dev hence hardcoding
SurveyReplicationImporter sri = new SurveyReplicationImporter();
sri.executeImport("http://watermapmonitordev.appspot.com",
"http://localhost:8888");
// sri.executeImport("http://localhost:8888",
// "http://localhost:8888");
} else if ("deleteSurveyResponses".equals(action)) {
if (req.getParameter("surveyId") == null) {
try {
resp.getWriter()
.println("surveyId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
deleteSurveyResponses(
Integer.parseInt(req.getParameter("surveyId")),
Integer.parseInt(req.getParameter("count")));
}
} else if ("fixNameQuestion".equals(action)) {
if (req.getParameter("questionId") == null) {
try {
resp.getWriter().println(
"questionId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
fixNameQuestion(req.getParameter("questionId"));
}
} else if ("createSurveyAssignment".equals(action)) {
Device device = new Device();
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
device.setPhoneNumber("1111111111");
device.setInServiceDate(new Date());
BaseDAO<Device> deviceDao = new BaseDAO<Device>(Device.class);
deviceDao.save(device);
SurveyAssignmentServiceImpl sasi = new SurveyAssignmentServiceImpl();
SurveyAssignmentDto dto = new SurveyAssignmentDto();
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
SurveyAssignment sa = new SurveyAssignment();
BaseDAO<SurveyAssignment> surveyAssignmentDao = new BaseDAO<SurveyAssignment>(
SurveyAssignment.class);
sa.setCreatedDateTime(new Date());
sa.setCreateUserId(-1L);
ArrayList<Long> deviceList = new ArrayList<Long>();
deviceList.add(device.getKey().getId());
sa.setDeviceIds(deviceList);
ArrayList<SurveyDto> surveyDtoList = new ArrayList<SurveyDto>();
for (Survey survey : surveyList) {
sa.addSurvey(survey.getKey().getId());
SurveyDto surveyDto = new SurveyDto();
surveyDto.setKeyId(survey.getKey().getId());
surveyDtoList.add(surveyDto);
}
sa.setStartDate(new Date());
sa.setEndDate(new Date());
sa.setName(new Date().toString());
DeviceDto deviceDto = new DeviceDto();
deviceDto.setKeyId(device.getKey().getId());
deviceDto.setPhoneNumber(device.getPhoneNumber());
ArrayList<DeviceDto> deviceDtoList = new ArrayList<DeviceDto>();
deviceDtoList.add(deviceDto);
dto.setDevices(deviceDtoList);
dto.setSurveys(surveyDtoList);
dto.setEndDate(new Date());
dto.setLanguage("en");
dto.setName("Test Assignment: " + new Date().toString());
dto.setStartDate(new Date());
sasi.saveSurveyAssignment(dto);
// sasi.deleteSurveyAssignment(dto);
} else if ("populateAssignmentId".equalsIgnoreCase(action)) {
populateAssignmentId(Long.parseLong(req
.getParameter("assignmentId")));
} else if ("testDSJQDelete".equals(action)) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq);
DeviceSurveyJobQueue dsjq2 = new DeviceSurveyJobQueue();
dsjq2.setDevicePhoneNumber("2019561591");
cal.add(Calendar.DAY_OF_MONTH, 20);
dsjq2.setEffectiveEndDate(cal.getTime());
dsjq2.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq2);
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> dsjqList = dsjqDao
.listAssignmentsWithEarlierExpirationDate(new Date());
for (DeviceSurveyJobQueue item : dsjqList) {
SurveyTaskUtil.spawnDeleteTask("deleteDeviceSurveyJobQueue",
item.getAssignmentId());
}
} else if ("loadDSJ".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey item : surveyList) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(item.getKey().getId());
dsjDAO.save(dsjq);
}
for (int i = 0; i < 20; i++) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(rand.nextLong());
dsjDAO.save(dsjq);
}
try {
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("deleteUnusedDSJQueue".equals(action)) {
try {
SurveyDAO surveyDao = new SurveyDAO();
List<Key> surveyIdList = surveyDao.listSurveyIds();
List<Long> ids = new ArrayList<Long>();
for (Key key : surveyIdList)
ids.add(key.getId());
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> deleteList = new ArrayList<DeviceSurveyJobQueue>();
for (DeviceSurveyJobQueue item : dsjqDao.listAllJobsInQueue()) {
Long dsjqSurveyId = item.getSurveyID();
Boolean found = ids.contains(dsjqSurveyId);
if (!found) {
deleteList.add(item);
resp.getWriter().println(
"Marking " + item.getId() + " survey: "
+ item.getSurveyID() + " for deletion");
}
}
dsjqDao.delete(deleteList);
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("testListTrace".equals(action)) {
listStacktrace();
} else if ("createEditorialContent".equals(action)) {
createEditorialContent(req.getParameter("pageName"));
} else if ("generateEditorialContent".equals(action)) {
try {
resp.getWriter().print(
generateEditorialContent(req.getParameter("pageName")));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("populateperms".equals(action)) {
populatePermissions();
} else if ("testnotif".equals(action)) {
sendNotification(req.getParameter("surveyId"));
} else if ("popsurvey".equals(action)) {
SurveyDAO sDao = new SurveyDAO();
List<Survey> sList = sDao.list(null);
QuestionDao questionDao = new QuestionDao();
List<Question> qList = questionDao.listQuestionByType(sList.get(0)
.getKey().getId(), Question.Type.FREE_TEXT);
SurveyInstanceDAO instDao = new SurveyInstanceDAO();
for (int i = 0; i < 10; i++) {
SurveyInstance instance = new SurveyInstance();
instance.setSurveyId(sList.get(0).getKey().getId());
instance = instDao.save(instance);
for (int j = 0; j < qList.size(); j++) {
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID(qList.get(j).getKey().getId() + "");
ans.setValue("" + j * i);
ans.setSurveyInstanceId(instance.getKey().getId());
// ans.setSurveyInstance(instance);
instDao.save(ans);
}
}
try {
resp.getWriter().print(sList.get(0).getKey().getId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testnotifhelper".equals(action)) {
NotificationHelper helper = new NotificationHelper();
helper.execute();
}
}
private void sendNotification(String surveyId) {
// com.google.appengine.api.taskqueue.Queue queue =
// com.google.appengine.api.taskqueue.QueueFactory.getQueue("notification");
Queue queue = QueueFactory.getQueue("notification");
queue.add(url("/notificationprocessor")
.param(NotificationRequest.DEST_PARAM,
"[email protected]||[email protected]")
.param(NotificationRequest.DEST_OPT_PARAM, "ATTACHMENT||LINK")
.param(NotificationRequest.ENTITY_PARAM, surveyId)
.param(NotificationRequest.TYPE_PARAM, "rawDataReport"));
}
private void populatePermissions() {
UserDao userDao = new UserDao();
List<Permission> permList = userDao.listPermissions();
if (permList == null) {
permList = new ArrayList<Permission>();
}
savePerm("Edit Survey", permList, userDao);
savePerm("Edit Users", permList, userDao);
savePerm("Edit Access Point", permList, userDao);
savePerm("Edit Editorial Content", permList, userDao);
savePerm("Import Survey Data", permList, userDao);
savePerm("Import Access Point Data", permList, userDao);
savePerm("Upload Survey Data", permList, userDao);
savePerm("Edit Raw Data", permList, userDao);
}
private void savePerm(String name, List<Permission> permList,
UserDao userDao) {
Permission p = new Permission(name);
boolean found = false;
for (Permission perm : permList) {
if (perm.equals(p)) {
found = true;
break;
}
}
if (!found) {
userDao.save(p);
}
}
private void setupTestUser() {
UserDao userDao = new UserDao();
User user = userDao.findUserByEmail("[email protected]");
String permissionList = "";
int i = 0;
List<Permission> pList = userDao.listPermissions();
for (Permission p : pList) {
permissionList += p.getCode();
if (i < pList.size())
permissionList += ",";
i++;
}
user.setPermissionList(permissionList);
userDao.save(user);
}
private String generateEditorialContent(String pageName) {
String content = "";
EditorialPageDao dao = new EditorialPageDao();
EditorialPage p = dao.findByTargetPage(pageName);
List<EditorialPageContent> contentList = dao.listContentByPage(p
.getKey().getId());
try {
RuntimeServices runtimeServices = RuntimeSingleton
.getRuntimeServices();
StringReader reader = new StringReader(p.getTemplate().getValue());
SimpleNode node = runtimeServices.parse(reader, "dynamicTemplate");
Template template = new Template();
template.setRuntimeServices(runtimeServices);
template.setData(node);
template.initDocument();
Context ctx = new VelocityContext();
ctx.put("pages", contentList);
StringWriter writer = new StringWriter();
template.merge(ctx, writer);
content = writer.toString();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not initialize velocity", e);
}
return content;
}
private void createEditorialContent(String pageName) {
EditorialPageDao dao = new EditorialPageDao();
EditorialPage page = new EditorialPage();
page.setTargetFileName(pageName);
page.setType("landing");
page.setTemplate(new Text(
"<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>"));
page = dao.save(page);
EditorialPageContent content = new EditorialPageContent();
List<EditorialPageContent> contentList = new ArrayList<EditorialPageContent>();
content.setHeading("Heading 1");
content.setText(new Text("this is some text"));
content.setSortOrder(1L);
content.setEditorialPageId(page.getKey().getId());
contentList.add(content);
content = new EditorialPageContent();
content.setHeading("Heading 2");
content.setText(new Text("this is more text"));
content.setSortOrder(2L);
content.setEditorialPageId(page.getKey().getId());
contentList.add(content);
dao.save(contentList);
}
private void listStacktrace() {
RemoteStacktraceDao traceDao = new RemoteStacktraceDao();
List<RemoteStacktrace> result = null;
result = traceDao.listStacktrace(null, null, false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, null, true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", null, true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", "12345", true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, "12345", true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", null, false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", "12345", false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, "12345", false, null);
if (result != null) {
System.out.println(result.size() + "");
}
}
private void populateAssignmentId(Long assignmentId) {
BaseDAO<SurveyAssignment> assignmentDao = new BaseDAO<SurveyAssignment>(
SurveyAssignment.class);
SurveyAssignment assignment = assignmentDao.getByKey(assignmentId);
DeviceSurveyJobQueueDAO jobDao = new DeviceSurveyJobQueueDAO();
if (assignment != null) {
for (Long sid : assignment.getSurveyIds()) {
jobDao.updateAssignmentIdForSurvey(sid, assignmentId);
}
}
}
private void fixNameQuestion(String questionId) {
Queue summQueue = QueueFactory.getQueue("dataUpdate");
summQueue.add(url("/app_worker/dataupdate").param("objectKey",
questionId + "").param("type", "NameQuestionFix"));
}
private boolean deleteSurveyResponses(Integer surveyId, Integer count) {
SurveyInstanceDAO dao = new SurveyInstanceDAO();
List<SurveyInstance> instances = dao.listSurveyInstanceBySurvey(
new Long(surveyId), count != null ? count : 100);
if (instances != null) {
for (SurveyInstance instance : instances) {
List<QuestionAnswerStore> questions = dao
.listQuestionAnswerStore(instance.getKey().getId(),
count);
if (questions != null) {
dao.delete(questions);
}
dao.delete(instance);
}
return true;
}
return false;
}
private void reprocessSurveys(String date) throws ParseException {
SurveyInstanceDAO dao = new SurveyInstanceDAO();
Date startDate = null;
if (date != null) {
DateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
startDate = sdf.parse(date);
List<SurveyInstance> instances = dao.listByDateRange(startDate,
null, null);
if (instances != null) {
AccessPointHelper aph = new AccessPointHelper();
for (SurveyInstance instance : instances) {
aph.processSurveyInstance(instance.getKey().getId() + "");
}
}
}
}
private boolean migratePointType(AccessPointType source,
AccessPointType dest) {
AccessPointDao pointDao = new AccessPointDao();
List<AccessPoint> list = pointDao.searchAccessPoints(null, null, null,
null, source.toString(), null, null, null, null, null, null);
if (list != null && list.size() > 0) {
for (AccessPoint point : list) {
point.setPointType(dest);
pointDao.save(point);
}
}
if (list != null && list.size() == 20) {
return true;
} else {
return false;
}
}
@SuppressWarnings("unchecked")
private <T extends BaseDomain> void deleteAll(Class<T> type) {
BaseDAO<T> baseDao = new BaseDAO(type);
List<T> items = baseDao.list("all");
if (items != null) {
for (T item : items) {
baseDao.delete(item);
}
}
}
private void createTestSurveyForEndToEnd() {
SurveyGroupDto sgd = new SurveyGroupDto();
sgd.setCode("E2E Test");
sgd.setDescription("end2end test");
SurveyDto surveyDto = new SurveyDto();
surveyDto.setDescription("e2e test");
SurveyServiceImpl surveySvc = new SurveyServiceImpl();
QuestionGroupDto qgd = new QuestionGroupDto();
qgd.setCode("Question Group 1");
qgd.setDescription("Question Group Desc");
QuestionDto qd = new QuestionDto();
qd.setText("Access Point Name:");
qd.setType(QuestionType.FREE_TEXT);
qgd.addQuestion(qd, 0);
qd = new QuestionDto();
qd.setText("Location:");
qd.setType(QuestionType.GEO);
qgd.addQuestion(qd, 1);
qd = new QuestionDto();
qd.setText("Photo");
qd.setType(QuestionType.PHOTO);
qgd.addQuestion(qd, 2);
surveyDto.addQuestionGroup(qgd);
surveyDto.setVersion("Version: 1");
sgd.addSurvey(surveyDto);
sgd = surveySvc.save(sgd);
System.out.println(sgd.getKeyId());
}
private void writeImageToResponse(HttpServletResponse resp, String urlString) {
resp.setContentType("image/jpeg");
try {
ServletOutputStream out = resp.getOutputStream();
URL url = new URL(urlString);
InputStream in = url.openStream();
byte[] buffer = new byte[2048];
int size;
while ((size = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, size);
}
in.close();
out.flush();
} catch (Exception ex) {
}
}
private void writeImageToResponse(HttpServletResponse resp,
byte[] imageBytes) {
resp.setContentType("image/jpeg");
try {
ServletOutputStream out = resp.getOutputStream();
out.write(imageBytes, 0, imageBytes.length);
out.flush();
} catch (Exception ex) {
}
}
private void createSurveyGroupGraph(HttpServletResponse resp) {
com.gallatinsystems.survey.dao.SurveyGroupDAO sgDao = new com.gallatinsystems.survey.dao.SurveyGroupDAO();
BaseDAO<Translation> tDao = new BaseDAO<Translation>(Translation.class);
for (Translation t : tDao.list("all"))
tDao.delete(t);
// clear out old surveys
List<SurveyGroup> sgList = sgDao.list("all");
for (SurveyGroup item : sgList)
sgDao.delete(item);
try {
resp.getWriter().println("Finished clearing surveyGroup table");
} catch (IOException e1) {
e1.printStackTrace();
}
SurveyDAO surveyDao = new SurveyDAO();
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
QuestionDao questionDao = new QuestionDao();
QuestionOptionDao questionOptionDao = new QuestionOptionDao();
QuestionHelpMediaDao helpDao = new QuestionHelpMediaDao();
for (int i = 0; i < 2; i++) {
com.gallatinsystems.survey.domain.SurveyGroup sg = new com.gallatinsystems.survey.domain.SurveyGroup();
sg.setCode(i + ":" + new Date());
sg.setName(i + ":" + new Date());
sg = sgDao.save(sg);
for (int j = 0; j < 2; j++) {
com.gallatinsystems.survey.domain.Survey survey = new com.gallatinsystems.survey.domain.Survey();
survey.setCode(j + ":" + new Date());
survey.setName(j + ":" + new Date());
survey.setSurveyGroupId(sg.getKey().getId());
survey.setPath(sg.getCode());
survey = surveyDao.save(survey);
Translation t = new Translation();
t.setLanguageCode("es");
t.setText(j + ":" + new Date());
t.setParentType(ParentType.SURVEY_NAME);
t.setParentId(survey.getKey().getId());
tDao.save(t);
survey.addTranslation(t);
for (int k = 0; k < 3; k++) {
com.gallatinsystems.survey.domain.QuestionGroup qg = new com.gallatinsystems.survey.domain.QuestionGroup();
qg.setName("en:" + j + new Date());
qg.setDesc("en:desc: " + j + new Date());
qg.setCode("en:" + j + new Date());
qg.setSurveyId(survey.getKey().getId());
qg.setOrder(k);
qg.setPath(sg.getCode() + "/" + survey.getCode());
qg = questionGroupDao.save(qg);
Translation t2 = new Translation();
t2.setLanguageCode("es");
t2.setParentType(ParentType.QUESTION_GROUP_NAME);
t2.setText("es:" + k + new Date());
t2.setParentId(qg.getKey().getId());
tDao.save(t2);
qg.addTranslation(t2);
for (int l = 0; l < 2; l++) {
com.gallatinsystems.survey.domain.Question q = new com.gallatinsystems.survey.domain.Question();
q.setType(Type.OPTION);
q.setAllowMultipleFlag(false);
q.setAllowOtherFlag(false);
q.setDependentFlag(false);
q.setMandatoryFlag(true);
q.setQuestionGroupId(qg.getKey().getId());
q.setOrder(l);
q.setText("en:" + l + ":" + new Date());
q.setTip("en:" + l + ":" + new Date());
q.setPath(sg.getCode() + "/" + survey.getCode() + "/"
+ qg.getCode());
q.setSurveyId(survey.getKey().getId());
q = questionDao.save(q);
Translation tq = new Translation();
tq.setLanguageCode("es");
tq.setText("es" + l + ":" + new Date());
tq.setParentType(ParentType.QUESTION_TEXT);
tq.setParentId(q.getKey().getId());
tDao.save(tq);
q.addTranslation(tq);
for (int m = 0; m < 10; m++) {
com.gallatinsystems.survey.domain.QuestionOption qo = new com.gallatinsystems.survey.domain.QuestionOption();
qo.setOrder(m);
qo.setText(m + ":" + new Date());
qo.setCode(m + ":" + new Date());
qo.setQuestionId(q.getKey().getId());
qo = questionOptionDao.save(qo);
Translation tqo = new Translation();
tqo.setLanguageCode("es");
tqo.setText("es:" + m + ":" + new Date());
tqo.setParentType(ParentType.QUESTION_OPTION);
tqo.setParentId(qo.getKey().getId());
tDao.save(tqo);
qo.addTranslation(tqo);
q.addQuestionOption(qo);
}
for (int n = 0; n < 10; n++) {
com.gallatinsystems.survey.domain.QuestionHelpMedia qhm = new com.gallatinsystems.survey.domain.QuestionHelpMedia();
qhm.setText("en:" + n + ":" + new Date());
qhm.setType(QuestionHelpMedia.Type.PHOTO);
qhm.setResourceUrl("http://test.com/" + n + ".jpg");
qhm.setQuestionId(q.getKey().getId());
qhm = helpDao.save(qhm);
Translation tqhm = new Translation();
tqhm.setLanguageCode("es");
tqhm.setText("es:" + n + ":" + new Date());
tqhm.setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT);
tqhm.setParentId(qhm.getKey().getId());
tDao.save(tqhm);
qhm.addTranslation(tqhm);
q.addHelpMedia(n, qhm);
}
qg.addQuestion(l, q);
}
survey.addQuestionGroup(k, qg);
}
sg.addSurvey(survey);
}
log.log(Level.INFO, "Finished Saving sg: " + sg.getKey().toString());
}
}
}
| GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java | package org.waterforpeople.mapping.app.web;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.datanucleus.store.appengine.query.JDOCursorHelper;
import org.waterforpeople.mapping.analytics.MapSummarizer;
import org.waterforpeople.mapping.analytics.dao.AccessPointStatusSummaryDao;
import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary;
import org.waterforpeople.mapping.app.gwt.client.device.DeviceDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyAssignmentDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType;
import org.waterforpeople.mapping.app.gwt.server.accesspoint.AccessPointManagerServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.devicefiles.DeviceFilesServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.survey.SurveyAssignmentServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.survey.SurveyServiceImpl;
import org.waterforpeople.mapping.dao.AccessPointDao;
import org.waterforpeople.mapping.dao.CommunityDao;
import org.waterforpeople.mapping.dao.DeviceFilesDao;
import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao;
import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao;
import org.waterforpeople.mapping.dao.SurveyContainerDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.dataexport.DeviceFilesReplicationImporter;
import org.waterforpeople.mapping.dataexport.SurveyReplicationImporter;
import org.waterforpeople.mapping.domain.AccessPoint;
import org.waterforpeople.mapping.domain.Community;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.SurveyAssignment;
import org.waterforpeople.mapping.domain.SurveyAttributeMapping;
import org.waterforpeople.mapping.domain.SurveyInstance;
import org.waterforpeople.mapping.domain.TechnologyType;
import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType;
import org.waterforpeople.mapping.domain.AccessPoint.Status;
import org.waterforpeople.mapping.domain.Status.StatusCode;
import org.waterforpeople.mapping.helper.AccessPointHelper;
import org.waterforpeople.mapping.helper.GeoRegionHelper;
import org.waterforpeople.mapping.helper.KMLHelper;
import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.gallatinsystems.common.util.ZipUtil;
import com.gallatinsystems.device.dao.DeviceDAO;
import com.gallatinsystems.device.domain.Device;
import com.gallatinsystems.device.domain.DeviceFiles;
import com.gallatinsystems.device.domain.DeviceSurveyJobQueue;
import com.gallatinsystems.device.domain.Device.DeviceType;
import com.gallatinsystems.diagnostics.dao.RemoteStacktraceDao;
import com.gallatinsystems.diagnostics.domain.RemoteStacktrace;
import com.gallatinsystems.editorial.dao.EditorialPageDao;
import com.gallatinsystems.editorial.domain.EditorialPage;
import com.gallatinsystems.editorial.domain.EditorialPageContent;
import com.gallatinsystems.editorial.domain.MapBalloonDefinition;
import com.gallatinsystems.editorial.domain.MapBalloonDefinition.BalloonType;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.framework.domain.BaseDomain;
import com.gallatinsystems.framework.exceptions.IllegalDeletionException;
import com.gallatinsystems.gis.geography.domain.Country;
import com.gallatinsystems.gis.location.GeoLocationServiceGeonamesImpl;
import com.gallatinsystems.gis.location.GeoPlace;
import com.gallatinsystems.gis.map.dao.MapFragmentDao;
import com.gallatinsystems.gis.map.dao.OGRFeatureDao;
import com.gallatinsystems.gis.map.domain.Geometry;
import com.gallatinsystems.gis.map.domain.MapFragment;
import com.gallatinsystems.gis.map.domain.OGRFeature;
import com.gallatinsystems.gis.map.domain.Geometry.GeometryType;
import com.gallatinsystems.gis.map.domain.MapFragment.FRAGMENTTYPE;
import com.gallatinsystems.notification.NotificationRequest;
import com.gallatinsystems.notification.helper.NotificationHelper;
import com.gallatinsystems.survey.dao.DeviceSurveyJobQueueDAO;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.QuestionHelpMediaDao;
import com.gallatinsystems.survey.dao.QuestionOptionDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyGroupDAO;
import com.gallatinsystems.survey.dao.SurveyTaskUtil;
import com.gallatinsystems.survey.dao.TranslationDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionHelpMedia;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyContainer;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.gallatinsystems.survey.domain.SurveyXMLFragment;
import com.gallatinsystems.survey.domain.Translation;
import com.gallatinsystems.survey.domain.Question.Type;
import com.gallatinsystems.survey.domain.Translation.ParentType;
import com.gallatinsystems.user.dao.UserDao;
import com.gallatinsystems.user.domain.Permission;
import com.gallatinsystems.user.domain.User;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
public class TestHarnessServlet extends HttpServlet {
private static Logger log = Logger.getLogger(TestHarnessServlet.class
.getName());
private static final long serialVersionUID = -5673118002247715049L;
@SuppressWarnings("unused")
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String action = req.getParameter("action");
if ("testSurveyOrdering".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
SurveyGroup sgItem = sgDao.list("all").get(0);
sgItem = sgDao.getByKey(sgItem.getKey().getId(), true);
} else if ("setupTestUser".equals(action)) {
setupTestUser();
} else if ("reorderQuestionsByCollectionDate".equals(action)) {
try {
Long questionGroupId = Long.parseLong(req
.getParameter("questionGroupId"));
QuestionDao qDao = new QuestionDao();
List<Question> qList = qDao
.listQuestionsByQuestionGroupOrderByCreatedDateTime(questionGroupId);
int i = 0;
for (Question q : qList) {
q.setOrder(i + 1);
qDao.save(q);
resp.getWriter().println(
q.getOrder() + " :Change: " + q.getText());
++i;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("genBalloonData".equals(action)) {
MapBalloonDefinition mpd = new MapBalloonDefinition();
mpd.setBalloonType(BalloonType.KML_WATER_POINT);
mpd
.setStyleData("@charset \"utf-8\"; body {font-family: Trebuchet MS, Arial, Helvetica, sans-serif;font-weight: bold;color: #6d6e71;}");
mpd.setName("WFPWaterPoint");
} else if ("deleteGeoData".equals(action)) {
try {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
for (OGRFeature item : ogrFeatureDao.list("all")) {
resp.getWriter().println(
"deleting: " + item.getCountryCode());
ogrFeatureDao.delete(item);
}
resp.getWriter().println("Finished");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testGeoLocation".equals(action)) {
OGRFeatureDao ogrFeatureDao = new OGRFeatureDao();
GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
String lat = req.getParameter("lat");
String lon = req.getParameter("lon");
GeoPlace geoPlace = gs.manualLookup(lat, lon);
try {
if (geoPlace != null)
resp.getWriter().println(
"Found: " + geoPlace.getCountryName() + ":"
+ geoPlace.getCountryCode() + " for " + lat
+ ", " + lon);
geoPlace = gs.manualLookup(lat, lon,
OGRFeature.FeatureType.SUB_COUNTRY_OTHER);
if (geoPlace != null)
resp.getWriter().println(
"Found: " + geoPlace.getCountryCode() + ":"
+ geoPlace.getSub1() + ":"
+ geoPlace.getSub2() + ":"
+ geoPlace.getSub3() + ":"
+ geoPlace.getSub4() + ":"
+ geoPlace.getSub5() + ":"
+ geoPlace.getSub6() + " for " + lat + ", "
+ lon);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("RemapAPToSub".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
} else if ("loadOGRFeature".equals(action)) {
OGRFeature ogrFeature = new OGRFeature();
ogrFeature.setName("clan-21061011");
ogrFeature.setProjectCoordinateSystemIdentifier("World_Mercator");
ogrFeature.setGeoCoordinateSystemIdentifier("GCS_WGS_1984");
ogrFeature.setDatumIdentifier("WGS_1984");
ogrFeature.setSpheroid(6378137D);
ogrFeature.setReciprocalOfFlattening(298.257223563);
ogrFeature.setCountryCode("LR");
ogrFeature.addBoundingBox(223700.015625, 481399.468750,
680781.375000, 945462.437500);
Geometry geo = new Geometry();
geo.setType(GeometryType.POLYGON);
String coords = "497974.5625 557051.875,498219.03125 557141.75,498655.34375 557169.4375,499001.65625 557100.1875,499250.96875 556933.9375,499167.875 556615.375,499230.1875 556407.625,499392.78125 556362.75,499385.90625 556279.875,499598.5 556067.3125,499680.25 555952.8125,499218.5625 554988.875,498775.65625 554860.1875,498674.5 554832.5625,498282.0 554734.4375,498020.34375 554554.5625,497709.59375 554374.6875,497614.84375 554374.6875,497519.46875 554369.1875,497297.3125 554359.9375,496852.96875 554355.3125,496621.125 554351.375,496695.75 554454.625,496771.59375 554604.625,496836.3125 554734.0625,496868.65625 554831.125,496847.09375 554863.4375,496760.8125 554863.4375,496663.75 554928.125,496620.625 554992.875,496555.90625 555025.1875,496448.0625 554992.875,496372.5625 555025.1875,496351.0 555133.0625,496415.71875 555197.75,496480.40625 555294.8125,496480.40625 555381.0625,496430.875 555430.75,496446.0625 555547.375,496490.53125 555849.625,496526.09375 556240.75,496721.65625 556596.375,496924.90625 556774.1875,497006.125 556845.25,497281.71875 556978.625,497610.625 556969.6875,497859.53125 556969.6875,497974.5625 557051.875";
for (String item : coords.split(",")) {
String[] coord = item.split(" ");
geo.addCoordinate(Double.parseDouble(coord[0]), Double
.parseDouble(coord[1]));
}
ogrFeature.setGeometry(geo);
ogrFeature.addGeoMeasure("CLNAME", "STRING", "Loisiana Township");
ogrFeature.addGeoMeasure("COUNT", "FLOAT", "1");
BaseDAO<OGRFeature> ogrDao = new BaseDAO<OGRFeature>(
OGRFeature.class);
ogrDao.save(ogrFeature);
try {
resp.getWriter()
.println("OGRFeature: " + ogrFeature.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("resetLRAP".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
Random rand = new Random();
for (AccessPoint ap : apDao.list("all")) {
if ((ap.getCountryCode() == null || ap.getCountryCode()
.equals("US"))
&& (ap.getLatitude() != null && ap.getLongitude() != null)) {
if (ap.getLatitude() > 5.0 && ap.getLatitude() < 11) {
if (ap.getLongitude() < -9
&& ap.getLongitude() > -11) {
ap.setCountryCode("LR");
apDao.save(ap);
resp
.getWriter()
.println(
"Found "
+ ap.getCommunityCode()
+ "mapped to US changing mapping to LR \n");
}
}
} else if (ap.getCommunityCode() == null) {
ap.setCommunityCode(rand.nextLong() + "");
apDao.save(ap);
resp.getWriter().println(
"Found " + ap.getCommunityCode()
+ "added random community code \n");
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("clearSurveyInstanceQAS".equals(action)) {
// QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
// for (QuestionAnswerStore qas : qasDao.list("all")) {
// qasDao.delete(qas);
// }
// SurveyInstanceDAO siDao = new SurveyInstanceDAO();
// for (SurveyInstance si : siDao.list("all")) {
// siDao.delete(si);
// }
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all"))
apDao.delete(ap);
} else if ("SurveyInstance".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
List<SurveyInstance> siList = siDao.listSurveyInstanceBySurveyId(
1362011L, null);
Cursor cursor = JDOCursorHelper.getCursor(siList);
int i = 0;
while (siList.size() > 0) {
for (SurveyInstance si : siList) {
System.out.println(i++ + " " + si.toString());
String surveyInstanceId = new Long(si.getKey().getId())
.toString();
Queue queue = QueueFactory.getDefaultQueue();
queue.add(url("/app_worker/surveytask").param("action",
"reprocessMapSurveyInstance").param("id",
surveyInstanceId));
log.info("submiting task for SurveyInstanceId: "
+ surveyInstanceId);
}
siList = siDao.listSurveyInstanceBySurveyId(1362011L, cursor
.toWebSafeString());
cursor = JDOCursorHelper.getCursor(siList);
}
System.out.println("finished");
} else if ("rotateImage".equals(action)) {
AccessPointManagerServiceImpl apmI = new AccessPointManagerServiceImpl();
String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg";
// String test2 =
// "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg";
writeImageToResponse(resp, test1);
apmI.setUploadS3Flag(false);
writeImageToResponse(resp, apmI.rotateImage(test1));
// apmI.rotateImage(test2);
} else if ("clearSurveyGroupGraph".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.delete(sgDao.list("all"));
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.delete(surveyDao.list("all"));
QuestionGroupDao qgDao = new QuestionGroupDao();
qgDao.delete(qgDao.list("all"));
QuestionDao qDao = new QuestionDao();
qDao.delete(qDao.list("all"));
QuestionHelpMediaDao qhDao = new QuestionHelpMediaDao();
qhDao.delete(qhDao.list("all"));
QuestionOptionDao qoDao = new QuestionOptionDao();
qoDao.delete(qoDao.list("all"));
TranslationDao tDao = new TranslationDao();
tDao.delete(tDao.list("all"));
/*
* createSurveyGroupGraph(resp); //SurveyGroupDAO sgDao = new
* SurveyGroupDAO(); List<SurveyGroup> sgList = sgDao.list("all");
* Survey survey = sgList.get(0).getSurveyList().get(0);
* QuestionAnswerStore qas = new QuestionAnswerStore();
* qas.setArbitratyNumber(1L);
* qas.setSurveyId(survey.getKey().getId()); qas.setQuestionID("1");
* qas.setValue("test"); QuestionAnswerStoreDao qasDao = new
* QuestionAnswerStoreDao(); qasDao.save(qas);
*
*
* for(SurveyGroup sg: sgList) sgDao.delete(sg);
*/
} else if ("replicateDeviceFiles".equals(action)) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
for (SurveyInstance si : siDao.list("all")) {
siDao.delete(si);
}
QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
for (QuestionAnswerStore qas : qasDao.list("all")) {
qasDao.delete(qas);
}
DeviceFilesDao dfDao = new DeviceFilesDao();
for (DeviceFiles df : dfDao.list("all")) {
dfDao.delete(df);
}
DeviceFilesReplicationImporter dfri = new DeviceFilesReplicationImporter();
dfri.executeImport("http://watermapmonitordev.appspot.com",
"http://localhost:8888");
Set<String> dfSet = new HashSet<String>();
for (DeviceFiles df : dfDao.list("all")) {
dfSet.add(df.getURI());
}
DeviceFilesServiceImpl dfsi = new DeviceFilesServiceImpl();
int i = 0;
try {
resp.getWriter().println(
"Found " + dfSet.size() + " distinct files to process");
for (String s : dfSet) {
dfsi.reprocessDeviceFile(s);
resp.getWriter().println(
"submitted " + s + " for reprocessing");
i++;
if (i > 10)
break;
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("addDeviceFiles".equals(action)) {
DeviceFilesDao dfDao = new DeviceFilesDao();
DeviceFiles df = new DeviceFiles();
df
.setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip");
df.setCreatedDateTime(new Date());
df.setPhoneNumber("a4:ed:4e:54:ef:6d");
df.setChecksum("1149406886");
df.setProcessedStatus(StatusCode.ERROR_INFLATING_ZIP);
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
java.util.Date date = new java.util.Date();
String dateTime = dateFormat.format(date);
df.setProcessDate(dateTime);
dfDao.save(df);
} else if ("testBaseDomain".equals(action)) {
SurveyDAO surveyDAO = new SurveyDAO();
String outString = surveyDAO.getForTest();
BaseDAO<AccessPoint> pointDao = new BaseDAO<AccessPoint>(
AccessPoint.class);
AccessPoint point = new AccessPoint();
point.setLatitude(78d);
point.setLongitude(43d);
pointDao.save(point);
try {
resp.getWriter().print(outString);
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("testSaveRegion".equals(action)) {
GeoRegionHelper geoHelp = new GeoRegionHelper();
ArrayList<String> regionLines = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
StringBuilder builder = new StringBuilder();
builder.append("1,").append("" + i).append(",test,").append(
20 + i + ",").append(30 + i + "\n");
regionLines.add(builder.toString());
}
geoHelp.processRegionsSurvey(regionLines);
try {
resp.getWriter().print("Save complete");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save test region", e);
}
} else if ("clearAccessPoint".equals(action)) {
try {
AccessPointDao apDao = new AccessPointDao();
for (AccessPoint ap : apDao.list("all")) {
apDao.delete(ap);
try {
resp.getWriter().print(
"Finished Deleting AP: " + ap.toString());
} catch (IOException e) {
log.log(Level.SEVERE, "Could not delete ap");
}
}
resp.getWriter().print("Deleted AccessPoints complete");
BaseDAO<AccessPointStatusSummary> apsDao = new BaseDAO<AccessPointStatusSummary>(
AccessPointStatusSummary.class);
for (AccessPointStatusSummary item : apsDao.list("all")) {
apsDao.delete(item);
}
resp.getWriter().print("Deleted AccessPointStatusSummary");
MapFragmentDao mfDao = new MapFragmentDao();
for (MapFragment item : mfDao.list("all")) {
mfDao.delete(item);
}
resp.getWriter().print("Cleared MapFragment Table");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not clear AP and APStatusSummary",
e);
}
} else if ("loadErrorPoints".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
AccessPointDao apDao = new AccessPointDao();
for (int j = 0; j < 1; j++) {
Double lat = 0.0;
Double lon = 0.0;
for (int i = 0; i < 5; i++) {
AccessPoint ap = new AccessPoint();
ap.setLatitude(lat);
ap.setLongitude(lon);
Calendar calendar = Calendar.getInstance();
Date today = new Date();
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1 * i);
System.out
.println("AP: " + ap.getLatitude() + "/"
+ ap.getLongitude() + "Date: "
+ calendar.getTime());
ap.setCollectionDate(calendar.getTime());
ap.setAltitude(0.0);
ap.setCommunityCode("test" + new Date());
ap.setCommunityName("test" + new Date());
ap.setPhotoURL("http://test.com");
ap.setPointType(AccessPoint.AccessPointType.WATER_POINT);
if (i == 0)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
else if (i == 1)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK);
else if (i == 2)
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
else
ap.setPointStatus(Status.NO_IMPROVED_SYSTEM);
if (i % 2 == 0)
ap.setTypeTechnologyString("Kiosk");
else
ap.setTypeTechnologyString("Afridev Handpump");
apDao.save(ap);
MapSummarizer ms = new MapSummarizer();
// ms.performSummarization("" + ap.getKey().getId(), "");
if (i % 50 == 0)
log.log(Level.INFO, "Loaded to " + i);
}
}
try {
resp.getWriter().println("Finished loading aps");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("loadLots".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
AccessPointDao apDao = new AccessPointDao();
for (int j = 0; j < 1; j++) {
double lat = -15 + (new Random().nextDouble() / 10);
double lon = 35 + (new Random().nextDouble() / 10);
for (int i = 0; i < 3000; i++) {
AccessPoint ap = new AccessPoint();
ap.setLatitude(lat);
ap.setLongitude(lon);
Calendar calendar = Calendar.getInstance();
Date today = new Date();
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1 * i);
System.out
.println("AP: " + ap.getLatitude() + "/"
+ ap.getLongitude() + "Date: "
+ calendar.getTime());
// ap.setCollectionDate(calendar.getTime());
ap.setAltitude(0.0);
ap.setCommunityCode("test" + new Date());
ap.setCommunityName("test" + new Date());
ap
.setPhotoURL("http://waterforpeople.s3.amazonaws.com/images/peru/pc28water.jpg");
ap.setProvideAdequateQuantity(true);
ap.setHasSystemBeenDown1DayFlag(false);
ap.setMeetGovtQualityStandardFlag(true);
ap.setMeetGovtQuantityStandardFlag(false);
ap.setCurrentManagementStructurePoint("Community Board");
ap.setDescription("Waterpoint");
ap.setDistrict("test district");
ap.setEstimatedHouseholds(100L);
ap.setEstimatedPeoplePerHouse(11L);
ap.setFarthestHouseholdfromPoint("Yes");
ap.setNumberOfHouseholdsUsingPoint(100L);
ap.setConstructionDateYear("2001");
ap.setCostPer(1.0);
ap.setCountryCode("MW");
ap.setConstructionDate(new Date());
ap.setCollectionDate(new Date());
ap.setPhotoName("Water point");
if (i % 2 == 0)
ap
.setPointType(AccessPoint.AccessPointType.WATER_POINT);
else if (i % 3 == 0)
ap
.setPointType(AccessPoint.AccessPointType.SANITATION_POINT);
else
ap
.setPointType(AccessPoint.AccessPointType.PUBLIC_INSTITUTION);
if (i == 0)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
else if (i == 1)
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_OK);
else if (i == 2)
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
else
ap.setPointStatus(Status.NO_IMPROVED_SYSTEM);
if (i % 2 == 0)
ap.setTypeTechnologyString("Kiosk");
else
ap.setTypeTechnologyString("Afridev Handpump");
apDao.save(ap);
MapSummarizer ms = new MapSummarizer();
// ms.performSummarization("" + ap.getKey().getId(), "");
if (i % 50 == 0)
log.log(Level.INFO, "Loaded to " + i);
}
}
try {
resp.getWriter().println("Finished loading aps");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("loadCountries".equals(action)) {
Country c = new Country();
c.setIsoAlpha2Code("HN");
c.setName("Honduras");
BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class);
countryDAO.save(c);
Country c2 = new Country();
c2.setIsoAlpha2Code("MW");
c2.setName("Malawi");
countryDAO.save(c2);
} else if ("testAPKml".equals(action)) {
MapFragmentDao mfDao = new MapFragmentDao();
BaseDAO<TechnologyType> ttDao = new BaseDAO<TechnologyType>(
TechnologyType.class);
List<TechnologyType> ttList = ttDao.list("all");
for (TechnologyType tt : ttList)
ttDao.delete(tt);
TechnologyType tt = new TechnologyType();
tt.setCode("Afridev Handpump");
tt.setName("Afridev Handpump");
ttDao.save(tt);
TechnologyType tt2 = new TechnologyType();
tt2.setCode("Kiosk");
tt2.setName("Kiosk");
ttDao.save(tt2);
KMLHelper kmlHelper = new KMLHelper();
kmlHelper.buildMap();
List<MapFragment> mfList = mfDao.searchMapFragments("ALL", null,
null, null, FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all",
null, null);
try {
for (MapFragment mfItem : mfList) {
String contents = ZipUtil
.unZip(mfItem.getBlob().getBytes());
log
.log(Level.INFO, "Contents Length: "
+ contents.length());
resp.setContentType("application/vnd.google-earth.kmz+xml");
ServletOutputStream out = resp.getOutputStream();
resp.setHeader("Content-Disposition",
"inline; filename=waterforpeoplemapping.kmz;");
out.write(mfItem.getBlob().getBytes());
out.flush();
}
} catch (IOException ie) {
log.log(Level.SEVERE, "Could not list fragment");
}
} else if ("deleteSurveyGraph".equals(action)) {
deleteAll(SurveyGroup.class);
deleteAll(Survey.class);
deleteAll(QuestionGroup.class);
deleteAll(Question.class);
deleteAll(Translation.class);
deleteAll(QuestionOption.class);
deleteAll(QuestionHelpMedia.class);
try {
resp.getWriter().println("Finished deleting survey graph");
} catch (IOException iex) {
log.log(Level.SEVERE, "couldn't delete surveyGraph" + iex);
}
}
else if ("saveSurveyGroupRefactor".equals(action)) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
createSurveyGroupGraph(resp);
try {
List<SurveyGroup> savedSurveyGroups = sgDao.list("all");
for (SurveyGroup sgItem : savedSurveyGroups) {
resp.getWriter().println("SG: " + sgItem.getCode());
for (Survey survey : sgItem.getSurveyList()) {
resp.getWriter().println(
" Survey:" + survey.getName());
for (Map.Entry<Integer, QuestionGroup> entry : survey
.getQuestionGroupMap().entrySet()) {
resp.getWriter().println(
" QuestionGroup: " + entry.getKey()
+ ":" + entry.getValue().getDesc());
for (Map.Entry<Integer, Question> questionEntry : entry
.getValue().getQuestionMap().entrySet()) {
resp.getWriter().println(
" Question"
+ questionEntry.getKey()
+ ":"
+ questionEntry.getValue()
.getText());
for (Map.Entry<Integer, QuestionHelpMedia> qhmEntry : questionEntry
.getValue().getQuestionHelpMediaMap()
.entrySet()) {
resp.getWriter().println(
" QuestionHelpMedia"
+ qhmEntry.getKey()
+ ":"
+ qhmEntry.getValue()
.getText());
/*
* for (Key tKey : qhmEntry.getValue()
* .getAltTextKeyList()) { Translation t =
* tDao.getByKey(tKey);
* resp.getWriter().println(
* " QHMAltText" +
* t.getLanguageCode() + ":" + t.getText());
* }
*/
}
}
}
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save sg");
}
} else if ("createAP".equals(action)) {
AccessPoint ap = new AccessPoint();
ap.setCollectionDate(new Date());
ap.setCommunityCode(new Random().toString());
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setCountryCode("SZ");
ap.setPointType(AccessPointType.WATER_POINT);
AccessPointHelper helper = new AccessPointHelper();
helper.saveAccessPoint(ap);
} else if ("createInstance".equals(action)) {
SurveyInstance si = new SurveyInstance();
si.setCollectionDate(new Date());
ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>();
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID("q2");
ans.setValue("Geneva");
store.add(ans);
si.setQuestionAnswersStore(store);
SurveyInstanceDAO dao = new SurveyInstanceDAO();
si = dao.save(si);
Queue summQueue = QueueFactory.getQueue("dataSummarization");
summQueue.add(url("/app_worker/datasummarization").param(
"objectKey", si.getKey().getId() + "").param("type",
"SurveyInstance"));
} else if ("createCommunity".equals(action)) {
CommunityDao dao = new CommunityDao();
Country c = new Country();
c.setIsoAlpha2Code("CA");
c.setName("Canada");
c.setDisplayName("Canada");
Community comm = new Community();
comm.setCommunityCode("ON");
dao.save(c);
comm.setCountryCode("CA");
comm.setLat(54.99);
comm.setLon(-74.72);
dao.save(comm);
c = new Country();
c.setIsoAlpha2Code("US");
c.setName("United States");
c.setDisplayName("Unites States");
comm = new Community();
comm.setCommunityCode("Omaha");
comm.setCountryCode("US");
comm.setLat(34.99);
comm.setLon(-74.72);
dao.save(c);
dao.save(comm);
} else if ("addPhone".equals(action)) {
String phoneNumber = req.getParameter("phoneNumber");
Device d = new Device();
d.setPhoneNumber(phoneNumber);
d.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
if (req.getParameter("esn") != null)
d.setEsn(req.getParameter("esn"));
if (req.getParameter("gallatinSoftwareManifest") != null)
d.setGallatinSoftwareManifest(req
.getParameter("gallatinSoftwareManifest"));
d.setInServiceDate(new Date());
DeviceDAO deviceDao = new DeviceDAO();
deviceDao.save(d);
try {
resp.getWriter().println("finished adding " + phoneNumber);
} catch (Exception e) {
e.printStackTrace();
}
} else if ("createAPSummary".equals(action)) {
AccessPointStatusSummary sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao();
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
} else if ("createApHistory".equals(action)) {
GregorianCalendar cal = new GregorianCalendar();
AccessPointHelper apHelper = new AccessPointHelper();
AccessPoint ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(300l);
ap.setCostPer(43.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(317l);
ap.setCostPer(40.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(37.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(34.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(338l);
ap.setCostPer(38.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(170l);
ap.setCostPer(19.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(201l);
ap.setCostPer(19.00);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(211l);
ap.setCostPer(17.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(220l);
ap.setCostPer(25.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(175l);
ap.setCostPer(24.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
} else if ("generateGeocells".equals(action)) {
AccessPointDao apDao = new AccessPointDao();
List<AccessPoint> apList = apDao.list(null);
if (apList != null) {
for (AccessPoint ap : apList) {
if (ap.getGeocells() == null
|| ap.getGeocells().size() == 0) {
if (ap.getLatitude() != null
&& ap.getLongitude() != null) {
ap
.setGeocells(GeocellManager
.generateGeoCell(new Point(ap
.getLatitude(), ap
.getLongitude())));
apDao.save(ap);
}
}
}
}
} else if ("loadExistingSurvey".equals(action)) {
SurveyGroup sg = new SurveyGroup();
sg.setKey(KeyFactory.createKey(SurveyGroup.class.getSimpleName(),
2L));
sg.setName("test" + new Date());
sg.setCode("test" + new Date());
SurveyGroupDAO sgDao = new SurveyGroupDAO();
sgDao.save(sg);
Survey s = new Survey();
s.setKey(KeyFactory.createKey(Survey.class.getSimpleName(), 2L));
s.setName("test" + new Date());
s.setSurveyGroupId(sg.getKey().getId());
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.save(s);
} else if ("saveAPMapping".equals(action)) {
SurveyAttributeMapping mapping = new SurveyAttributeMapping();
mapping.setAttributeName("status");
mapping.setObjectName(AccessPoint.class.getCanonicalName());
mapping.setSurveyId(1L);
mapping.setSurveyQuestionId("q1");
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
samDao.save(mapping);
} else if ("listAPMapping".equals(action)) {
SurveyAttributeMappingDao samDao = new SurveyAttributeMappingDao();
List<SurveyAttributeMapping> mappings = samDao
.listMappingsBySurvey(1L);
if (mappings != null) {
System.out.println(mappings.size());
}
} else if ("saveSurveyGroup".equals(action)) {
try {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
List<SurveyGroup> sgList = sgDao.list("all");
for (SurveyGroup sg : sgList) {
sgDao.delete(sg);
}
resp.getWriter().println("Deleted all survey groups");
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey survey : surveyList) {
try {
surveyDao.delete(survey);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all surveys");
resp.getWriter().println("Deleted all surveysurveygroupassocs");
QuestionGroupDao qgDao = new QuestionGroupDao();
List<QuestionGroup> qgList = qgDao.list("all");
for (QuestionGroup qg : qgList) {
qgDao.delete(qg);
}
resp.getWriter().println("Deleted all question groups");
QuestionDao qDao = new QuestionDao();
List<Question> qList = qDao.list("all");
for (Question q : qList) {
try {
qDao.delete(q);
} catch (IllegalDeletionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resp.getWriter().println("Deleted all Questions");
QuestionOptionDao qoDao = new QuestionOptionDao();
List<QuestionOption> qoList = qoDao.list("all");
for (QuestionOption qo : qoList)
qoDao.delete(qo);
resp.getWriter().println("Deleted all QuestionOptions");
resp.getWriter().println("Deleted all questions");
resp.getWriter().println(
"Finished deleting and reloading SurveyGroup graph");
} catch (IOException e) {
e.printStackTrace();
}
} else if ("testPublishSurvey".equals(action)) {
try {
SurveyGroupDto sgDto = new SurveyServiceImpl()
.listSurveyGroups(null, true, false, false).get(0);
resp.getWriter().println(
"Got Survey Group: " + sgDto.getCode() + " Survey: "
+ sgDto.getSurveyList().get(0).getKeyId());
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(sgDto.getSurveyList()
.get(0).getKeyId());
if (sc != null) {
scDao.delete(sc);
resp.getWriter().println(
"Deleted existing SurveyContainer for: "
+ sgDto.getSurveyList().get(0).getKeyId());
}
resp.getWriter().println(
"Result of publishing survey: "
+ new SurveyServiceImpl().publishSurvey(sgDto
.getSurveyList().get(0).getKeyId()));
sc = scDao.findBySurveyId(sgDto.getSurveyList().get(0)
.getKeyId());
resp.getWriter().println(
"Survey Document result from publish: \n\n\n\n"
+ sc.getSurveyDocument().getValue());
} catch (IOException ex) {
ex.printStackTrace();
}
} else if ("createTestSurveyForEndToEnd".equals(action)) {
createTestSurveyForEndToEnd();
} else if ("deleteSurveyFragments".equals(action)) {
deleteAll(SurveyXMLFragment.class);
} else if ("migratePIToSchool".equals(action)) {
try {
resp.getWriter().println(
"Has more? "
+ migratePointType(
AccessPointType.PUBLIC_INSTITUTION,
AccessPointType.SCHOOL));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("createDevice".equals(action)) {
DeviceDAO devDao = new DeviceDAO();
Device device = new Device();
device.setPhoneNumber("9175667663");
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
devDao.save(device);
} else if ("reprocessSurveys".equals(action)) {
try {
reprocessSurveys(req.getParameter("date"));
} catch (ParseException e) {
try {
resp.getWriter().println("Couldn't reprocess: " + e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else if ("importallsurveys".equals(action)) {
// Only run in dev hence hardcoding
SurveyReplicationImporter sri = new SurveyReplicationImporter();
sri.executeImport("http://watermapmonitordev.appspot.com",
"http://localhost:8888");
// sri.executeImport("http://localhost:8888",
// "http://localhost:8888");
} else if ("deleteSurveyResponses".equals(action)) {
if (req.getParameter("surveyId") == null) {
try {
resp.getWriter()
.println("surveyId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
deleteSurveyResponses(Integer.parseInt(req
.getParameter("surveyId")), Integer.parseInt(req
.getParameter("count")));
}
} else if ("fixNameQuestion".equals(action)) {
if (req.getParameter("questionId") == null) {
try {
resp.getWriter().println(
"questionId is a required parameter");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
fixNameQuestion(req.getParameter("questionId"));
}
} else if ("createSurveyAssignment".equals(action)) {
Device device = new Device();
device.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
device.setPhoneNumber("1111111111");
device.setInServiceDate(new Date());
BaseDAO<Device> deviceDao = new BaseDAO<Device>(Device.class);
deviceDao.save(device);
SurveyAssignmentServiceImpl sasi = new SurveyAssignmentServiceImpl();
SurveyAssignmentDto dto = new SurveyAssignmentDto();
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
SurveyAssignment sa = new SurveyAssignment();
BaseDAO<SurveyAssignment> surveyAssignmentDao = new BaseDAO<SurveyAssignment>(
SurveyAssignment.class);
sa.setCreatedDateTime(new Date());
sa.setCreateUserId(-1L);
ArrayList<Long> deviceList = new ArrayList<Long>();
deviceList.add(device.getKey().getId());
sa.setDeviceIds(deviceList);
ArrayList<SurveyDto> surveyDtoList = new ArrayList<SurveyDto>();
for (Survey survey : surveyList) {
sa.addSurvey(survey.getKey().getId());
SurveyDto surveyDto = new SurveyDto();
surveyDto.setKeyId(survey.getKey().getId());
surveyDtoList.add(surveyDto);
}
sa.setStartDate(new Date());
sa.setEndDate(new Date());
sa.setName(new Date().toString());
DeviceDto deviceDto = new DeviceDto();
deviceDto.setKeyId(device.getKey().getId());
deviceDto.setPhoneNumber(device.getPhoneNumber());
ArrayList<DeviceDto> deviceDtoList = new ArrayList<DeviceDto>();
deviceDtoList.add(deviceDto);
dto.setDevices(deviceDtoList);
dto.setSurveys(surveyDtoList);
dto.setEndDate(new Date());
dto.setLanguage("en");
dto.setName("Test Assignment: " + new Date().toString());
dto.setStartDate(new Date());
sasi.saveSurveyAssignment(dto);
// sasi.deleteSurveyAssignment(dto);
} else if ("populateAssignmentId".equalsIgnoreCase(action)) {
populateAssignmentId(Long.parseLong(req
.getParameter("assignmentId")));
} else if ("testDSJQDelete".equals(action)) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq);
DeviceSurveyJobQueue dsjq2 = new DeviceSurveyJobQueue();
dsjq2.setDevicePhoneNumber("2019561591");
cal.add(Calendar.DAY_OF_MONTH, 20);
dsjq2.setEffectiveEndDate(cal.getTime());
dsjq2.setAssignmentId(rand.nextLong());
dsjDAO.save(dsjq2);
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> dsjqList = dsjqDao
.listAssignmentsWithEarlierExpirationDate(new Date());
for (DeviceSurveyJobQueue item : dsjqList) {
SurveyTaskUtil.spawnDeleteTask("deleteDeviceSurveyJobQueue",
item.getAssignmentId());
}
} else if ("loadDSJ".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
List<Survey> surveyList = surveyDao.list("all");
for (Survey item : surveyList) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(item.getKey().getId());
dsjDAO.save(dsjq);
}
for (int i = 0; i < 20; i++) {
DeviceSurveyJobQueueDAO dsjDAO = new DeviceSurveyJobQueueDAO();
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -10);
Date then = cal.getTime();
DeviceSurveyJobQueue dsjq = new DeviceSurveyJobQueue();
dsjq.setDevicePhoneNumber("2019561591");
dsjq.setEffectiveEndDate(then);
Random rand = new Random();
dsjq.setAssignmentId(rand.nextLong());
dsjq.setSurveyID(rand.nextLong());
dsjDAO.save(dsjq);
}
try {
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("deleteUnusedDSJQueue".equals(action)) {
try {
SurveyDAO surveyDao = new SurveyDAO();
List<Key> surveyIdList = surveyDao.listSurveyIds();
List<Long> ids = new ArrayList<Long>();
for (Key key : surveyIdList)
ids.add(key.getId());
DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO();
List<DeviceSurveyJobQueue> deleteList = new ArrayList<DeviceSurveyJobQueue>();
for (DeviceSurveyJobQueue item : dsjqDao.listAllJobsInQueue()) {
Long dsjqSurveyId = item.getSurveyID();
Boolean found = ids.contains(dsjqSurveyId);
if (!found) {
deleteList.add(item);
resp.getWriter().println(
"Marking " + item.getId() + " survey: "
+ item.getSurveyID() + " for deletion");
}
}
dsjqDao.delete(deleteList);
resp.getWriter().println("finished");
} catch (IOException e1) {
e1.printStackTrace();
}
} else if ("testListTrace".equals(action)) {
listStacktrace();
} else if ("createEditorialContent".equals(action)) {
createEditorialContent(req.getParameter("pageName"));
} else if ("generateEditorialContent".equals(action)) {
try {
resp.getWriter().print(
generateEditorialContent(req.getParameter("pageName")));
} catch (IOException e) {
e.printStackTrace();
}
} else if ("populateperms".equals(action)) {
populatePermissions();
} else if ("testnotif".equals(action)) {
sendNotification(req.getParameter("surveyId"));
} else if ("popsurvey".equals(action)) {
SurveyDAO sDao = new SurveyDAO();
List<Survey> sList = sDao.list(null);
QuestionDao questionDao = new QuestionDao();
List<Question> qList = questionDao.listQuestionByType(sList.get(0)
.getKey().getId(), Question.Type.FREE_TEXT);
SurveyInstanceDAO instDao = new SurveyInstanceDAO();
for (int i = 0; i < 10; i++) {
SurveyInstance instance = new SurveyInstance();
instance.setSurveyId(sList.get(0).getKey().getId());
instance = instDao.save(instance);
for (int j = 0; j < qList.size(); j++) {
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID(qList.get(j).getKey().getId() + "");
ans.setValue("" + j * i);
ans.setSurveyInstanceId(instance.getKey().getId());
// ans.setSurveyInstance(instance);
instDao.save(ans);
}
}
try {
resp.getWriter().print(sList.get(0).getKey().getId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("testnotifhelper".equals(action)) {
NotificationHelper helper = new NotificationHelper();
helper.execute();
}
}
private void sendNotification(String surveyId) {
// com.google.appengine.api.taskqueue.Queue queue =
// com.google.appengine.api.taskqueue.QueueFactory.getQueue("notification");
Queue queue = QueueFactory.getQueue("notification");
queue.add(url("/notificationprocessor").param(
NotificationRequest.DEST_PARAM,
"[email protected]||[email protected]")
.param(NotificationRequest.DEST_OPT_PARAM, "ATTACHMENT||LINK")
.param(NotificationRequest.ENTITY_PARAM, surveyId).param(
NotificationRequest.TYPE_PARAM, "rawDataReport"));
}
private void populatePermissions() {
UserDao userDao = new UserDao();
List<Permission> permList = userDao.listPermissions();
if (permList == null) {
permList = new ArrayList<Permission>();
}
savePerm("Edit Survey", permList, userDao);
savePerm("Edit Users", permList, userDao);
savePerm("Edit Access Point", permList, userDao);
savePerm("Edit Editorial Content", permList, userDao);
savePerm("Import Survey Data", permList, userDao);
savePerm("Import Access Point Data", permList, userDao);
savePerm("Upload Survey Data", permList, userDao);
savePerm("Edit Raw Data", permList, userDao);
}
private void savePerm(String name, List<Permission> permList,
UserDao userDao) {
Permission p = new Permission(name);
boolean found = false;
for (Permission perm : permList) {
if (perm.equals(p)) {
found = true;
break;
}
}
if (!found) {
userDao.save(p);
}
}
private void setupTestUser() {
UserDao userDao = new UserDao();
User user = userDao.findUserByEmail("[email protected]");
String permissionList = "";
int i = 0;
List<Permission> pList = userDao.listPermissions();
for (Permission p : pList) {
permissionList += p.getCode();
if (i < pList.size())
permissionList += ",";
i++;
}
user.setPermissionList(permissionList);
userDao.save(user);
}
private String generateEditorialContent(String pageName) {
String content = "";
EditorialPageDao dao = new EditorialPageDao();
EditorialPage p = dao.findByTargetPage(pageName);
List<EditorialPageContent> contentList = dao.listContentByPage(p
.getKey().getId());
try {
RuntimeServices runtimeServices = RuntimeSingleton
.getRuntimeServices();
StringReader reader = new StringReader(p.getTemplate().getValue());
SimpleNode node = runtimeServices.parse(reader, "dynamicTemplate");
Template template = new Template();
template.setRuntimeServices(runtimeServices);
template.setData(node);
template.initDocument();
Context ctx = new VelocityContext();
ctx.put("pages", contentList);
StringWriter writer = new StringWriter();
template.merge(ctx, writer);
content = writer.toString();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not initialize velocity", e);
}
return content;
}
private void createEditorialContent(String pageName) {
EditorialPageDao dao = new EditorialPageDao();
EditorialPage page = new EditorialPage();
page.setTargetFileName(pageName);
page.setType("landing");
page
.setTemplate(new Text(
"<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>"));
page = dao.save(page);
EditorialPageContent content = new EditorialPageContent();
List<EditorialPageContent> contentList = new ArrayList<EditorialPageContent>();
content.setHeading("Heading 1");
content.setText(new Text("this is some text"));
content.setSortOrder(1L);
content.setEditorialPageId(page.getKey().getId());
contentList.add(content);
content = new EditorialPageContent();
content.setHeading("Heading 2");
content.setText(new Text("this is more text"));
content.setSortOrder(2L);
content.setEditorialPageId(page.getKey().getId());
contentList.add(content);
dao.save(contentList);
}
private void listStacktrace() {
RemoteStacktraceDao traceDao = new RemoteStacktraceDao();
List<RemoteStacktrace> result = null;
result = traceDao.listStacktrace(null, null, false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, null, true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", null, true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", "12345", true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, "12345", true, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", null, false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace("12345", "12345", false, null);
if (result != null) {
System.out.println(result.size() + "");
}
result = traceDao.listStacktrace(null, "12345", false, null);
if (result != null) {
System.out.println(result.size() + "");
}
}
private void populateAssignmentId(Long assignmentId) {
BaseDAO<SurveyAssignment> assignmentDao = new BaseDAO<SurveyAssignment>(
SurveyAssignment.class);
SurveyAssignment assignment = assignmentDao.getByKey(assignmentId);
DeviceSurveyJobQueueDAO jobDao = new DeviceSurveyJobQueueDAO();
if (assignment != null) {
for (Long sid : assignment.getSurveyIds()) {
jobDao.updateAssignmentIdForSurvey(sid, assignmentId);
}
}
}
private void fixNameQuestion(String questionId) {
Queue summQueue = QueueFactory.getQueue("dataUpdate");
summQueue.add(url("/app_worker/dataupdate").param("objectKey",
questionId + "").param("type", "NameQuestionFix"));
}
private boolean deleteSurveyResponses(Integer surveyId, Integer count) {
SurveyInstanceDAO dao = new SurveyInstanceDAO();
List<SurveyInstance> instances = dao.listSurveyInstanceBySurvey(
new Long(surveyId), count != null ? count : 100);
if (instances != null) {
for (SurveyInstance instance : instances) {
List<QuestionAnswerStore> questions = dao
.listQuestionAnswerStore(instance.getKey().getId(),
count);
if (questions != null) {
dao.delete(questions);
}
dao.delete(instance);
}
return true;
}
return false;
}
private void reprocessSurveys(String date) throws ParseException {
SurveyInstanceDAO dao = new SurveyInstanceDAO();
Date startDate = null;
if (date != null) {
DateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
startDate = sdf.parse(date);
List<SurveyInstance> instances = dao.listByDateRange(startDate,
null, null);
if (instances != null) {
AccessPointHelper aph = new AccessPointHelper();
for (SurveyInstance instance : instances) {
aph.processSurveyInstance(instance.getKey().getId() + "");
}
}
}
}
private boolean migratePointType(AccessPointType source,
AccessPointType dest) {
AccessPointDao pointDao = new AccessPointDao();
List<AccessPoint> list = pointDao.searchAccessPoints(null, null, null,
null, source.toString(), null, null, null, null, null, null);
if (list != null && list.size() > 0) {
for (AccessPoint point : list) {
point.setPointType(dest);
pointDao.save(point);
}
}
if (list != null && list.size() == 20) {
return true;
} else {
return false;
}
}
@SuppressWarnings("unchecked")
private <T extends BaseDomain> void deleteAll(Class<T> type) {
BaseDAO<T> baseDao = new BaseDAO(type);
List<T> items = baseDao.list("all");
if (items != null) {
for (T item : items) {
baseDao.delete(item);
}
}
}
private void createTestSurveyForEndToEnd() {
SurveyGroupDto sgd = new SurveyGroupDto();
sgd.setCode("E2E Test");
sgd.setDescription("end2end test");
SurveyDto surveyDto = new SurveyDto();
surveyDto.setDescription("e2e test");
SurveyServiceImpl surveySvc = new SurveyServiceImpl();
QuestionGroupDto qgd = new QuestionGroupDto();
qgd.setCode("Question Group 1");
qgd.setDescription("Question Group Desc");
QuestionDto qd = new QuestionDto();
qd.setText("Access Point Name:");
qd.setType(QuestionType.FREE_TEXT);
qgd.addQuestion(qd, 0);
qd = new QuestionDto();
qd.setText("Location:");
qd.setType(QuestionType.GEO);
qgd.addQuestion(qd, 1);
qd = new QuestionDto();
qd.setText("Photo");
qd.setType(QuestionType.PHOTO);
qgd.addQuestion(qd, 2);
surveyDto.addQuestionGroup(qgd);
surveyDto.setVersion("Version: 1");
sgd.addSurvey(surveyDto);
sgd = surveySvc.save(sgd);
System.out.println(sgd.getKeyId());
}
private void writeImageToResponse(HttpServletResponse resp, String urlString) {
resp.setContentType("image/jpeg");
try {
ServletOutputStream out = resp.getOutputStream();
URL url = new URL(urlString);
InputStream in = url.openStream();
byte[] buffer = new byte[2048];
int size;
while ((size = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, size);
}
in.close();
out.flush();
} catch (Exception ex) {
}
}
private void writeImageToResponse(HttpServletResponse resp,
byte[] imageBytes) {
resp.setContentType("image/jpeg");
try {
ServletOutputStream out = resp.getOutputStream();
out.write(imageBytes, 0, imageBytes.length);
out.flush();
} catch (Exception ex) {
}
}
private void createSurveyGroupGraph(HttpServletResponse resp) {
com.gallatinsystems.survey.dao.SurveyGroupDAO sgDao = new com.gallatinsystems.survey.dao.SurveyGroupDAO();
BaseDAO<Translation> tDao = new BaseDAO<Translation>(Translation.class);
for (Translation t : tDao.list("all"))
tDao.delete(t);
// clear out old surveys
List<SurveyGroup> sgList = sgDao.list("all");
for (SurveyGroup item : sgList)
sgDao.delete(item);
try {
resp.getWriter().println("Finished clearing surveyGroup table");
} catch (IOException e1) {
e1.printStackTrace();
}
SurveyDAO surveyDao = new SurveyDAO();
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
QuestionDao questionDao = new QuestionDao();
QuestionOptionDao questionOptionDao = new QuestionOptionDao();
QuestionHelpMediaDao helpDao = new QuestionHelpMediaDao();
for (int i = 0; i < 2; i++) {
com.gallatinsystems.survey.domain.SurveyGroup sg = new com.gallatinsystems.survey.domain.SurveyGroup();
sg.setCode(i + ":" + new Date());
sg.setName(i + ":" + new Date());
sg = sgDao.save(sg);
for (int j = 0; j < 2; j++) {
com.gallatinsystems.survey.domain.Survey survey = new com.gallatinsystems.survey.domain.Survey();
survey.setCode(j + ":" + new Date());
survey.setName(j + ":" + new Date());
survey.setSurveyGroupId(sg.getKey().getId());
survey.setPath(sg.getCode());
survey = surveyDao.save(survey);
Translation t = new Translation();
t.setLanguageCode("es");
t.setText(j + ":" + new Date());
t.setParentType(ParentType.SURVEY_NAME);
t.setParentId(survey.getKey().getId());
tDao.save(t);
survey.addTranslation(t);
for (int k = 0; k < 3; k++) {
com.gallatinsystems.survey.domain.QuestionGroup qg = new com.gallatinsystems.survey.domain.QuestionGroup();
qg.setName("en:" + j + new Date());
qg.setDesc("en:desc: " + j + new Date());
qg.setCode("en:" + j + new Date());
qg.setSurveyId(survey.getKey().getId());
qg.setOrder(k);
qg.setPath(sg.getCode() + "/" + survey.getCode());
qg = questionGroupDao.save(qg);
Translation t2 = new Translation();
t2.setLanguageCode("es");
t2.setParentType(ParentType.QUESTION_GROUP_NAME);
t2.setText("es:" + k + new Date());
t2.setParentId(qg.getKey().getId());
tDao.save(t2);
qg.addTranslation(t2);
for (int l = 0; l < 2; l++) {
com.gallatinsystems.survey.domain.Question q = new com.gallatinsystems.survey.domain.Question();
q.setType(Type.OPTION);
q.setAllowMultipleFlag(false);
q.setAllowOtherFlag(false);
q.setDependentFlag(false);
q.setMandatoryFlag(true);
q.setQuestionGroupId(qg.getKey().getId());
q.setOrder(l);
q.setText("en:" + l + ":" + new Date());
q.setTip("en:" + l + ":" + new Date());
q.setPath(sg.getCode() + "/" + survey.getCode() + "/"
+ qg.getCode());
q.setSurveyId(survey.getKey().getId());
q = questionDao.save(q);
Translation tq = new Translation();
tq.setLanguageCode("es");
tq.setText("es" + l + ":" + new Date());
tq.setParentType(ParentType.QUESTION_TEXT);
tq.setParentId(q.getKey().getId());
tDao.save(tq);
q.addTranslation(tq);
for (int m = 0; m < 10; m++) {
com.gallatinsystems.survey.domain.QuestionOption qo = new com.gallatinsystems.survey.domain.QuestionOption();
qo.setOrder(m);
qo.setText(m + ":" + new Date());
qo.setCode(m + ":" + new Date());
qo.setQuestionId(q.getKey().getId());
qo = questionOptionDao.save(qo);
Translation tqo = new Translation();
tqo.setLanguageCode("es");
tqo.setText("es:" + m + ":" + new Date());
tqo.setParentType(ParentType.QUESTION_OPTION);
tqo.setParentId(qo.getKey().getId());
tDao.save(tqo);
qo.addTranslation(tqo);
q.addQuestionOption(qo);
}
for (int n = 0; n < 10; n++) {
com.gallatinsystems.survey.domain.QuestionHelpMedia qhm = new com.gallatinsystems.survey.domain.QuestionHelpMedia();
qhm.setText("en:" + n + ":" + new Date());
qhm.setType(QuestionHelpMedia.Type.PHOTO);
qhm.setResourceUrl("http://test.com/" + n + ".jpg");
qhm.setQuestionId(q.getKey().getId());
qhm = helpDao.save(qhm);
Translation tqhm = new Translation();
tqhm.setLanguageCode("es");
tqhm.setText("es:" + n + ":" + new Date());
tqhm
.setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT);
tqhm.setParentId(qhm.getKey().getId());
tDao.save(tqhm);
qhm.addTranslation(tqhm);
q.addHelpMedia(n, qhm);
}
qg.addQuestion(l, q);
}
survey.addQuestionGroup(k, qg);
}
sg.addSurvey(survey);
}
log
.log(Level.INFO, "Finished Saving sg: "
+ sg.getKey().toString());
}
}
}
| Modified reorder by survey
| GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java | Modified reorder by survey | <ide><path>AE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
<ide> setupTestUser();
<ide> } else if ("reorderQuestionsByCollectionDate".equals(action)) {
<ide> try {
<del> Long questionGroupId = Long.parseLong(req
<del> .getParameter("questionGroupId"));
<add> Long surveyId = Long.parseLong(req.getParameter("surveyId"));
<add> SurveyDAO surveyDao = new SurveyDAO();
<ide> QuestionDao qDao = new QuestionDao();
<ide>
<del> List<Question> qList = qDao
<del> .listQuestionsByQuestionGroupOrderByCreatedDateTime(questionGroupId);
<add> Survey survey = surveyDao.loadFullSurvey(surveyId);
<ide> int i = 0;
<del> for (Question q : qList) {
<del> q.setOrder(i + 1);
<del> qDao.save(q);
<del> resp.getWriter().println(
<del> q.getOrder() + " :Change: " + q.getText());
<del> ++i;
<add> for (Map.Entry<Integer, QuestionGroup> qGEntry : survey
<add> .getQuestionGroupMap().entrySet()) {
<add> List<Question> qList = qDao
<add> .listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
<add> .getValue().getKey().getId());
<add> for (Question q : qDao
<add> .listQuestionsByQuestionGroupOrderByCreatedDateTime(qGEntry
<add> .getValue().getKey().getId())) {
<add> q.setOrder(i + 1);
<add> qDao.save(q);
<add> resp.getWriter().println(
<add> q.getOrder() + " :Change: " + q.getText());
<add> ++i;
<add> }
<ide> }
<ide> } catch (IOException e) {
<ide> // TODO Auto-generated catch block
<ide> } else if ("genBalloonData".equals(action)) {
<ide> MapBalloonDefinition mpd = new MapBalloonDefinition();
<ide> mpd.setBalloonType(BalloonType.KML_WATER_POINT);
<del> mpd
<del> .setStyleData("@charset \"utf-8\"; body {font-family: Trebuchet MS, Arial, Helvetica, sans-serif;font-weight: bold;color: #6d6e71;}");
<add> mpd.setStyleData("@charset \"utf-8\"; body {font-family: Trebuchet MS, Arial, Helvetica, sans-serif;font-weight: bold;color: #6d6e71;}");
<ide> mpd.setName("WFPWaterPoint");
<ide>
<ide> } else if ("deleteGeoData".equals(action)) {
<ide> String coords = "497974.5625 557051.875,498219.03125 557141.75,498655.34375 557169.4375,499001.65625 557100.1875,499250.96875 556933.9375,499167.875 556615.375,499230.1875 556407.625,499392.78125 556362.75,499385.90625 556279.875,499598.5 556067.3125,499680.25 555952.8125,499218.5625 554988.875,498775.65625 554860.1875,498674.5 554832.5625,498282.0 554734.4375,498020.34375 554554.5625,497709.59375 554374.6875,497614.84375 554374.6875,497519.46875 554369.1875,497297.3125 554359.9375,496852.96875 554355.3125,496621.125 554351.375,496695.75 554454.625,496771.59375 554604.625,496836.3125 554734.0625,496868.65625 554831.125,496847.09375 554863.4375,496760.8125 554863.4375,496663.75 554928.125,496620.625 554992.875,496555.90625 555025.1875,496448.0625 554992.875,496372.5625 555025.1875,496351.0 555133.0625,496415.71875 555197.75,496480.40625 555294.8125,496480.40625 555381.0625,496430.875 555430.75,496446.0625 555547.375,496490.53125 555849.625,496526.09375 556240.75,496721.65625 556596.375,496924.90625 556774.1875,497006.125 556845.25,497281.71875 556978.625,497610.625 556969.6875,497859.53125 556969.6875,497974.5625 557051.875";
<ide> for (String item : coords.split(",")) {
<ide> String[] coord = item.split(" ");
<del> geo.addCoordinate(Double.parseDouble(coord[0]), Double
<del> .parseDouble(coord[1]));
<add> geo.addCoordinate(Double.parseDouble(coord[0]),
<add> Double.parseDouble(coord[1]));
<ide> }
<ide> ogrFeature.setGeometry(geo);
<ide> ogrFeature.addGeoMeasure("CLNAME", "STRING", "Loisiana Township");
<ide> && ap.getLongitude() > -11) {
<ide> ap.setCountryCode("LR");
<ide> apDao.save(ap);
<del> resp
<del> .getWriter()
<add> resp.getWriter()
<ide> .println(
<ide> "Found "
<ide> + ap.getCommunityCode()
<ide> log.info("submiting task for SurveyInstanceId: "
<ide> + surveyInstanceId);
<ide> }
<del> siList = siDao.listSurveyInstanceBySurveyId(1362011L, cursor
<del> .toWebSafeString());
<add> siList = siDao.listSurveyInstanceBySurveyId(1362011L,
<add> cursor.toWebSafeString());
<ide> cursor = JDOCursorHelper.getCursor(siList);
<ide> }
<ide> System.out.println("finished");
<ide> DeviceFilesDao dfDao = new DeviceFilesDao();
<ide>
<ide> DeviceFiles df = new DeviceFiles();
<del> df
<del> .setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip");
<add> df.setURI("http://waterforpeople.s3.amazonaws.com/devicezip/wfp1737657928520.zip");
<ide> df.setCreatedDateTime(new Date());
<ide> df.setPhoneNumber("a4:ed:4e:54:ef:6d");
<ide> df.setChecksum("1149406886");
<ide> ArrayList<String> regionLines = new ArrayList<String>();
<ide> for (int i = 0; i < 10; i++) {
<ide> StringBuilder builder = new StringBuilder();
<del> builder.append("1,").append("" + i).append(",test,").append(
<del> 20 + i + ",").append(30 + i + "\n");
<add> builder.append("1,").append("" + i).append(",test,")
<add> .append(20 + i + ",").append(30 + i + "\n");
<ide> regionLines.add(builder.toString());
<ide> }
<ide> geoHelp.processRegionsSurvey(regionLines);
<ide> ap.setAltitude(0.0);
<ide> ap.setCommunityCode("test" + new Date());
<ide> ap.setCommunityName("test" + new Date());
<del> ap
<del> .setPhotoURL("http://waterforpeople.s3.amazonaws.com/images/peru/pc28water.jpg");
<add> ap.setPhotoURL("http://waterforpeople.s3.amazonaws.com/images/peru/pc28water.jpg");
<ide> ap.setProvideAdequateQuantity(true);
<ide> ap.setHasSystemBeenDown1DayFlag(false);
<ide> ap.setMeetGovtQualityStandardFlag(true);
<ide> ap.setCollectionDate(new Date());
<ide> ap.setPhotoName("Water point");
<ide> if (i % 2 == 0)
<del> ap
<del> .setPointType(AccessPoint.AccessPointType.WATER_POINT);
<add> ap.setPointType(AccessPoint.AccessPointType.WATER_POINT);
<ide> else if (i % 3 == 0)
<del> ap
<del> .setPointType(AccessPoint.AccessPointType.SANITATION_POINT);
<add> ap.setPointType(AccessPoint.AccessPointType.SANITATION_POINT);
<ide> else
<del> ap
<del> .setPointType(AccessPoint.AccessPointType.PUBLIC_INSTITUTION);
<add> ap.setPointType(AccessPoint.AccessPointType.PUBLIC_INSTITUTION);
<ide> if (i == 0)
<ide> ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
<ide> else if (i == 1)
<ide> for (MapFragment mfItem : mfList) {
<ide> String contents = ZipUtil
<ide> .unZip(mfItem.getBlob().getBytes());
<del> log
<del> .log(Level.INFO, "Contents Length: "
<del> + contents.length());
<add> log.log(Level.INFO, "Contents Length: " + contents.length());
<ide> resp.setContentType("application/vnd.google-earth.kmz+xml");
<ide> ServletOutputStream out = resp.getOutputStream();
<ide> resp.setHeader("Content-Disposition",
<ide> || ap.getGeocells().size() == 0) {
<ide> if (ap.getLatitude() != null
<ide> && ap.getLongitude() != null) {
<del> ap
<del> .setGeocells(GeocellManager
<del> .generateGeoCell(new Point(ap
<del> .getLatitude(), ap
<del> .getLongitude())));
<add> ap.setGeocells(GeocellManager.generateGeoCell(new Point(
<add> ap.getLatitude(), ap.getLongitude())));
<ide> apDao.save(ap);
<ide> }
<ide> }
<ide> }
<ide> } else {
<ide>
<del> deleteSurveyResponses(Integer.parseInt(req
<del> .getParameter("surveyId")), Integer.parseInt(req
<del> .getParameter("count")));
<add> deleteSurveyResponses(
<add> Integer.parseInt(req.getParameter("surveyId")),
<add> Integer.parseInt(req.getParameter("count")));
<ide> }
<ide> } else if ("fixNameQuestion".equals(action)) {
<ide> if (req.getParameter("questionId") == null) {
<ide> // com.google.appengine.api.taskqueue.QueueFactory.getQueue("notification");
<ide> Queue queue = QueueFactory.getQueue("notification");
<ide>
<del> queue.add(url("/notificationprocessor").param(
<del> NotificationRequest.DEST_PARAM,
<del> "[email protected]||[email protected]")
<add> queue.add(url("/notificationprocessor")
<add> .param(NotificationRequest.DEST_PARAM,
<add> "[email protected]||[email protected]")
<ide> .param(NotificationRequest.DEST_OPT_PARAM, "ATTACHMENT||LINK")
<del> .param(NotificationRequest.ENTITY_PARAM, surveyId).param(
<del> NotificationRequest.TYPE_PARAM, "rawDataReport"));
<add> .param(NotificationRequest.ENTITY_PARAM, surveyId)
<add> .param(NotificationRequest.TYPE_PARAM, "rawDataReport"));
<ide> }
<ide>
<ide> private void populatePermissions() {
<ide> EditorialPage page = new EditorialPage();
<ide> page.setTargetFileName(pageName);
<ide> page.setType("landing");
<del> page
<del> .setTemplate(new Text(
<del> "<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>"));
<add> page.setTemplate(new Text(
<add> "<html><head><title>Test Generated</title></head><body><h1>This is a test</h1><ul>#foreach( $pageContent in $pages )<li>$pageContent.heading : $pageContent.text.value</li>#end</ul>"));
<ide> page = dao.save(page);
<ide> EditorialPageContent content = new EditorialPageContent();
<ide> List<EditorialPageContent> contentList = new ArrayList<EditorialPageContent>();
<ide> Translation tqhm = new Translation();
<ide> tqhm.setLanguageCode("es");
<ide> tqhm.setText("es:" + n + ":" + new Date());
<del> tqhm
<del> .setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT);
<add> tqhm.setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT);
<ide> tqhm.setParentId(qhm.getKey().getId());
<ide> tDao.save(tqhm);
<ide> qhm.addTranslation(tqhm);
<ide> }
<ide> sg.addSurvey(survey);
<ide> }
<del> log
<del> .log(Level.INFO, "Finished Saving sg: "
<del> + sg.getKey().toString());
<add> log.log(Level.INFO, "Finished Saving sg: " + sg.getKey().toString());
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 9b2c8774e8f9dce9d64dd2703d30bc3935deb55c | 0 | b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl | /*
* Copyright 2011-2020 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.core.rest.branches;
import static com.b2international.snowowl.snomed.core.rest.CodeSystemVersionRestRequests.getNextAvailableEffectiveDate;
import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.createComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.deleteComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.getComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.updateComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedRefSetRestRequests.updateRefSetComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedRefSetRestRequests.updateRefSetMemberEffectiveTime;
import static com.b2international.snowowl.snomed.core.rest.SnomedRestFixtures.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertFalse;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.b2international.commons.exceptions.BadRequestException;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.branch.BranchPathUtils;
import com.b2international.snowowl.core.date.DateFormats;
import com.b2international.snowowl.core.date.EffectiveTimes;
import com.b2international.snowowl.core.merge.Merge;
import com.b2international.snowowl.snomed.common.SnomedConstants.Concepts;
import com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants;
import com.b2international.snowowl.snomed.core.domain.Acceptability;
import com.b2international.snowowl.snomed.core.domain.AssociationTarget;
import com.b2international.snowowl.snomed.core.domain.InactivationProperties;
import com.b2international.snowowl.snomed.core.domain.SnomedConcept;
import com.b2international.snowowl.snomed.core.rest.AbstractSnomedApiTest;
import com.b2international.snowowl.snomed.core.rest.SnomedComponentType;
import com.google.common.collect.ImmutableMap;
/**
* Contains test cases for the branch rebase and merge functionality.
* <p>
* All scenarios that result in a content conflict should be placed in {@link SnomedMergeConflictTest} instead.
*
* @since 2.0
*/
public class SnomedMergeApiTest extends AbstractSnomedApiTest {
private static void rebaseConceptDeletionOverChange(IBranchPath parentPath, IBranchPath childPath, String conceptId) {
final Map<?, ?> changeOnParent = ImmutableMap.builder()
.put("definitionStatusId", Concepts.FULLY_DEFINED)
.put("commitComment", "Changed definition status on parent")
.build();
updateComponent(parentPath, SnomedComponentType.CONCEPT, conceptId, changeOnParent).statusCode(204);
deleteComponent(childPath, SnomedComponentType.CONCEPT, conceptId, false).statusCode(204);
merge(parentPath, childPath, "Rebased concept deletion over concept change").body("status", equalTo(Merge.Status.COMPLETED.name()));
}
@Test
public void mergeNewConceptForward() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String conceptId = createNewConcept(a);
merge(a, branchPath, "Merged new concept from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.CONCEPT, conceptId).statusCode(200);
getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(200);
}
@Test
public void mergeNewConceptForwardWithChildBranchDelete() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String conceptId = createNewConcept(a);
merge(a, branchPath, "Merged new concept from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
branching.deleteBranch(a).statusCode(204);
// getComponent(a, SnomedComponentType.CONCEPT, conceptId).statusCode(404);
SnomedConcept concept = getConcept(conceptId, "descriptions(),relationships()");
assertFalse(concept.getDescriptions().isEmpty());
assertFalse(concept.getRelationships().isEmpty());
}
@Test
public void mergeNewDescriptionForward() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String descriptionId = createNewDescription(a);
merge(a, branchPath, "Merged new description from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
getComponent(branchPath, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
}
@Test
public void mergeNewRelationshipForward() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
String relationshipId = createNewRelationship(a);
merge(a, branchPath, "Merged new relationship from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
}
@Test
public void noMergeWithNonExistentReview() throws BadRequestException {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
createNewConcept(a);
merge(a, branchPath, "Merged new concept from child branch with non-existent review ID", "non-existent-id")
.body("status", equalTo(Merge.Status.FAILED.name()));
}
// @Test
// public void noMergeNewConceptDiverged() {
// final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
// createBranch(a).statusCode(201);
//
// final String concept1Id = createNewConcept(a);
// final String concept2Id = createNewConcept(branchPath);
//
// getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(404);
// getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
// getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
//
// merge(a, branchPath, "Merged new concept from diverged branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
//
// getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(404);
// getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
// getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
// }
// @Test
// public void noMergeNewDescriptionDiverged() {
// IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
// createBranch(a).statusCode(201);
//
// String description1Id = createNewDescription(a);
// String description2Id = createNewDescription(branchPath);
//
// getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
// getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
// getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(404);
//
// merge(a, branchPath, "Merged new description from diverged branch").body("status", equalTo(Merge.Status.FAILED.name()));
//
// getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
// getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
// getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(404);
// }
// @Test
// public void noMergeNewRelationshipDiverged() {
// IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
// createBranch(a).statusCode(201);
//
// String relationship1Id = createNewRelationship(a);
// String relationship2Id = createNewRelationship(branchPath);
//
// getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(404);
// getComponent(a, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(200);
// getComponent(a, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(404);
//
// merge(a, branchPath, "Merged new relationship from diverged branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
//
// getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(404);
// getComponent(a, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(200);
// getComponent(a, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(404);
// }
@Test
public void mergeNewConceptToUnrelatedBranch() {
final IBranchPath v1 = BranchPathUtils.createPath(branchPath, "v1");
branching.createBranch(v1).statusCode(201);
// Concept 1 is created on the two branches' common ancestor
final String concept1Id = createNewConcept(branchPath);
final IBranchPath v2 = BranchPathUtils.createPath(branchPath, "v2");
branching.createBranch(v2).statusCode(201);
final IBranchPath a = BranchPathUtils.createPath(v1, "extension-old");
branching.createBranch(a).statusCode(201);
final IBranchPath b = BranchPathUtils.createPath(v2, "extension-new");
branching.createBranch(b).statusCode(201);
// Concept 2 is initially only visible on branch "extension-old"
final String concept2Id = createNewConcept(a);
getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(404);
getComponent(b, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
merge(a, b, "Merged new concept from unrelated branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(b, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
getComponent(b, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
}
@Test
public void mergeNewDescriptionToUnrelatedBranch() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final IBranchPath b = BranchPathUtils.createPath(branchPath, "b");
branching.createBranch(b).statusCode(201);
final String descriptionId = createNewDescription(a);
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
merge(a, b, "Merged new description from unrelated branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
}
@Test
public void mergeNewRelationshipToUnrelatedBranch() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final IBranchPath b = BranchPathUtils.createPath(branchPath, "b");
branching.createBranch(b).statusCode(201);
final String relationshipId = createNewRelationship(a);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(404);
merge(a, b, "Merged new relationship from unrelated branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
}
@Test
public void mergeReactivatedConcept() {
final String conceptId = createInactiveConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
reactivateConcept(a, conceptId);
merge(a, branchPath, "Merged reactivation from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId, "descriptions()", "relationships()").statusCode(200)
.body("active", equalTo(true))
.body("descriptions.items[0].active", equalTo(true))
.body("descriptions.items[1].active", equalTo(true))
// TODO check removal of CONCEPT_NON_CURRENT
.body("relationships.items[0].active", equalTo(true));
}
@Test
public void rebaseReactivatedConcept() {
final String concept1Id = createInactiveConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
reactivateConcept(a, concept1Id);
// Create concept 2 on "branchPath" so that "a" can be rebased
final String concept2Id = createNewConcept(branchPath);
merge(branchPath, a, "Rebased reactivation on child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Concept 1 should be active on "a", but still inactive on "branchPath"
getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id, "descriptions()", "relationships()").statusCode(200)
.body("active", equalTo(false))
.body("descriptions.items[0].active", equalTo(true))
.body("descriptions.items[1].active", equalTo(true))
.body("relationships.items[0].active", equalTo(false));
getComponent(a, SnomedComponentType.CONCEPT, concept1Id, "descriptions()", "relationships()").statusCode(200)
.body("active", equalTo(true))
.body("descriptions.items[0].active", equalTo(true))
.body("descriptions.items[1].active", equalTo(true))
.body("relationships.items[0].active", equalTo(true));
// Concept 2 should be visible everywhere
getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
}
@Test
public void rebaseNewConceptDiverged() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String concept1Id = createNewConcept(branchPath);
final String concept2Id = createNewConcept(a);
getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(404);
getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
merge(branchPath, a, "Rebased new concept").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Concept 1 from the parent becomes visible on the child after rebasing
getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
// Concept 2 should still not be present on the parent, however
getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
}
@Test
public void rebaseNewDescriptionDiverged() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String description1Id = createNewDescription(branchPath);
final String description2Id = createNewDescription(a);
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
merge(branchPath, a, "Rebased new description").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Description 1 from the parent becomes visible on the child after rebasing
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
// Description 2 should still not be present on the parent, however
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
}
@Test
public void rebaseNewRelationshipDiverged() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String relationship1Id = createNewRelationship(branchPath);
final String relationship2Id = createNewRelationship(a);
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(404);
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(404);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(200);
merge(branchPath, a, "Rebased new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Relationship 1 from the parent becomes visible on the child after rebasing
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
// Relationship 2 should still not be present on the parent, however
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(404);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(200);
}
@Test
public void rebaseNewConceptStale() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final IBranchPath b = BranchPathUtils.createPath(a, "b");
branching.createBranch(b).statusCode(201);
final String concept1Id = createNewConcept(b);
final String concept2Id = createNewConcept(a);
final String concept3Id = createNewConcept(branchPath);
merge(branchPath, a, "Rebased new concept on child over new concept on parent").body("status", equalTo(Merge.Status.COMPLETED.name()));
// "a" now knows about concept 3
getComponent(branchPath, SnomedComponentType.CONCEPT, concept3Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept3Id).statusCode(200);
// "b" is now in STALE state, and doesn't know about either concept 2 or 3
getComponent(b, SnomedComponentType.CONCEPT, concept3Id).statusCode(404);
getComponent(b, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
merge(a, b, "Rebased new concept on nested child over new concepts on child").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Now "b" should see all three concepts
getComponent(b, SnomedComponentType.CONCEPT, concept3Id).statusCode(200);
getComponent(b, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
getComponent(b, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
}
@Test
public void rebaseChangedConceptOnParentDeletedOnBranch() {
final String conceptId = createNewConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
rebaseConceptDeletionOverChange(branchPath, a, conceptId);
// Concept should still be present on parent, and deleted on child
getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(200).body("definitionStatusId", equalTo(Concepts.FULLY_DEFINED));
getComponent(a, SnomedComponentType.CONCEPT, conceptId).statusCode(404);
}
@Test
public void rebaseChangedDescriptionOnParentDeletedOnBranch() {
final String descriptionId = createNewDescription(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
changeCaseSignificance(branchPath, descriptionId); // Parent branch changes to CaseSignificance.ENTIRE_TERM_CASE_SENSITIVE
deleteComponent(a, SnomedComponentType.DESCRIPTION, descriptionId, false).statusCode(204);
merge(branchPath, a, "Rebased deletion over case significance change").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200).body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_SENSITIVE));
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
}
@Test
public void rebaseAndMergeChangedOnParentDeletedOnBranch() {
final String conceptId = createNewConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
rebaseConceptDeletionOverChange(branchPath, a, conceptId);
merge(a, branchPath, "Merged concept deletion").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Concept should now be deleted everywhere
getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(404);
getComponent(a, SnomedComponentType.CONCEPT, conceptId).statusCode(404);
}
@Test
public void rebaseAndMergeChangedDescription() {
final String description1Id = createNewDescription(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String description2Id = createNewDescription(branchPath);
final Map<?, ?> requestBody = ImmutableMap.builder()
.put("caseSignificanceId", Concepts.ENTIRE_TERM_CASE_INSENSITIVE)
.put("moduleId", Concepts.MODULE_ROOT)
.put("commitComment", "Changed case significance and module on child")
.build();
updateComponent(a, SnomedComponentType.DESCRIPTION, description1Id, requestBody);
merge(branchPath, a, "Rebased description change over new description creation").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Description 2 is now visible on both parent and child
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
// Description 1 retains the changes on child, keeps the original values on parent
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ONLY_INITIAL_CHARACTER_CASE_INSENSITIVE))
.body("moduleId", equalTo(Concepts.MODULE_SCT_CORE));
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_INSENSITIVE))
.body("moduleId", equalTo(Concepts.MODULE_ROOT));
merge(a, branchPath, "Merged description change to parent").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
// Description 1 changes are visible everywhere
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_INSENSITIVE))
.body("moduleId", equalTo(Concepts.MODULE_ROOT));
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_INSENSITIVE))
.body("moduleId", equalTo(Concepts.MODULE_ROOT));
}
@Test
public void rebaseAndMergeNewDescriptionBothDeleted() {
final String description1Id = createNewDescription(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String description2Id = createNewDescription(branchPath);
deleteComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id, false).statusCode(204);
deleteComponent(a, SnomedComponentType.DESCRIPTION, description1Id, false).statusCode(204);
/*
* The rebase sees that the same thing has already happened on the parent branch, and does not
* add an empty commit to the new instance of the child; it will be in UP_TO_DATE state and can
* not be promoted.
*/
merge(branchPath, a, "Rebased description dual deletion over description creation").body("status", equalTo(Merge.Status.COMPLETED.name()));
merge(a, branchPath, "Merged description dual deletion").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Description 1 is now deleted on both branches
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
// Description 2 should be present, however
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
}
@Test
public void rebaseOverReusedRelationshipId() {
final String relationshipId = createNewRelationship(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
deleteComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId, false).statusCode(204);
final Map<?, ?> requestBody = ImmutableMap.builder()
.put("sourceId", Concepts.ROOT_CONCEPT)
.put("moduleId", Concepts.MODULE_SCT_CORE)
.put("typeId", Concepts.FINDING_SITE)
.put("destinationId", Concepts.ROOT_CONCEPT)
.put("id", relationshipId)
.put("commitComment", "Created new relationship on parent with same SCTID")
.build();
createComponent(branchPath, SnomedComponentType.RELATIONSHIP, requestBody).statusCode(201);
// Different relationships before rebase
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("typeId", equalTo(Concepts.FINDING_SITE));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("typeId", equalTo(Concepts.PART_OF));
merge(branchPath, a, "Rebase after new relationship creation on parent").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Same relationships after rebase
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("typeId", equalTo(Concepts.FINDING_SITE));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("typeId", equalTo(Concepts.FINDING_SITE));
}
@Test
public void rebaseTextDefinitions() throws Exception {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
// Create two new text definitions with "cross-shaped" acceptability on child
final String textDefinition1Id = createNewTextDefinition(a, ImmutableMap.of(Concepts.REFSET_LANGUAGE_TYPE_UK, Acceptability.PREFERRED, Concepts.REFSET_LANGUAGE_TYPE_US, Acceptability.ACCEPTABLE));
final String textDefinition2Id = createNewTextDefinition(a, ImmutableMap.of(Concepts.REFSET_LANGUAGE_TYPE_UK, Acceptability.ACCEPTABLE, Concepts.REFSET_LANGUAGE_TYPE_US, Acceptability.PREFERRED));
// Create change on parent
final String relationshipId = createNewRelationship(branchPath);
merge(branchPath, a, "Rebased new text definitions over new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Relationship should be visible on both branches
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
// Text definitions are only on the child, however
getComponent(branchPath, SnomedComponentType.DESCRIPTION, textDefinition1Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, textDefinition1Id).statusCode(200);
getComponent(branchPath, SnomedComponentType.DESCRIPTION, textDefinition2Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, textDefinition2Id).statusCode(200);
}
@Test
public void rebaseStaleBranchWithChangesOnDeletedContent() throws Exception {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String relationshipId = createNewRelationship(a);
final String descriptionId = createNewDescription(a);
final IBranchPath b = BranchPathUtils.createPath(a, "b");
branching.createBranch(b).statusCode(201);
deleteComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId, false).statusCode(204);
deleteComponent(a, SnomedComponentType.DESCRIPTION, descriptionId, false).statusCode(204);
changeCaseSignificance(b, descriptionId);
changeRelationshipGroup(b, relationshipId);
// Make change on "branchPath" so "a" can be rebased
createNewRelationship(branchPath);
merge(branchPath, a, "Rebased component deletion over new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// "b" should be STALE at this point, try to rebase it, it should pass and the components should be deleted
merge(a, b, "Rebased component updates over deletion").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Verify that the two deleted components are really deleted
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(404);
}
@Test
public void rebaseStaleBranchWithChangesOnNewContent() throws Exception {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String relationshipId = createNewRelationship(a);
final String descriptionId = createNewDescription(a);
final IBranchPath b = BranchPathUtils.createPath(a, "b");
branching.createBranch(b).statusCode(201);
changeCaseSignificance(b, descriptionId);
changeRelationshipGroup(b, relationshipId);
// Make change on "branchPath" so "a" can be rebased
createNewRelationship(branchPath);
merge(branchPath, a, "Rebased new components over new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId)
.statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ONLY_INITIAL_CHARACTER_CASE_INSENSITIVE));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId)
.statusCode(200)
.body("group", equalTo(0));
// "b" should be STALE at this point, try to rebase it, it should pass and the components should still exist with changed content
merge(a, b, "Rebased changed components over new components").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Verify that the two components have the modified values
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200).body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_SENSITIVE));
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("group", equalTo(99));
}
@Test
public void rebaseStaleBranchWithDeleteOnChangedContent() throws Exception {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String relationshipId = createNewRelationship(a);
final String descriptionId = createNewDescription(a);
final IBranchPath b = BranchPathUtils.createPath(a, "b");
branching.createBranch(b).statusCode(201);
// Make changes on branch "a"
changeCaseSignificance(a, descriptionId);
changeRelationshipGroup(a, relationshipId);
// Delete description on branch "b"
deleteComponent(b, SnomedComponentType.DESCRIPTION, descriptionId, false).statusCode(204);
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
// Make change on "branchPath" so "a" can be rebased
createNewRelationship(branchPath);
merge(branchPath, a, "Rebased changed components over new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// "b" should be STALE at this point, try to rebase it, it should pass and the description should be deleted
merge(a, b, "Rebased description deletion over changed components").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Verify that the relationship has the modified values, and the description stayed deleted
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("group", equalTo(99));
}
@Test
@Ignore("Currently always fails due to merge policy")
public void rebaseChangedConceptOnBranchDeletedOnParent() {
final String conceptId = createNewConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final Map<?, ?> requestBody = ImmutableMap.builder()
.put("definitionStatusId", Concepts.FULLY_DEFINED)
.put("commitComment", "Changed definition status on child")
.build();
updateComponent(a, SnomedComponentType.CONCEPT, conceptId, requestBody).statusCode(204);
deleteComponent(branchPath, SnomedComponentType.CONCEPT, conceptId, false).statusCode(204);
merge(branchPath, a, "Rebased concept change over deletion").body("status", equalTo(Merge.Status.COMPLETED.name()));
}
@Test
public void rebaseUnsetEffectiveTimeOnSource() {
final String memberId = createNewRefSetMember(branchPath);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(getNextAvailableEffectiveDate(SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME));
updateRefSetMemberEffectiveTime(branchPath, memberId, calendar.getTime());
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
calendar.add(Calendar.DATE, 1);
updateRefSetMemberEffectiveTime(branchPath, memberId, calendar.getTime()); // Parent increases the effective time by one day
final Map<?, ?> childRequest = ImmutableMap.builder()
.put("active", false)
.put("commitComment", "Inactivated reference set member")
.build();
updateRefSetComponent(a, SnomedComponentType.MEMBER, memberId, childRequest, false).statusCode(204); // Child unsets it and inactivates the member
merge(branchPath, a, "Rebased update over effective time change").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.MEMBER, memberId).statusCode(200)
.body("released", equalTo(true))
.body("effectiveTime", equalTo(EffectiveTimes.format(calendar.getTime(), DateFormats.SHORT)))
.body("active", equalTo(true));
getComponent(a, SnomedComponentType.MEMBER, memberId).statusCode(200)
.body("released", equalTo(true))
.body("effectiveTime", nullValue())
.body("active", equalTo(false));
}
@Test
public void rebaseUnsetEffectiveTimeOnTarget() {
final String memberId = createNewRefSetMember(branchPath);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(getNextAvailableEffectiveDate(SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME));
updateRefSetMemberEffectiveTime(branchPath, memberId, calendar.getTime());
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final Map<?, ?> parentRequest = ImmutableMap.builder()
.put("active", false)
.put("commitComment", "Inactivated reference set member")
.build();
updateRefSetComponent(branchPath, SnomedComponentType.MEMBER, memberId, parentRequest, false).statusCode(204); // Parent unsets the effective time and inactivates the member
calendar.add(Calendar.DATE, 1);
updateRefSetMemberEffectiveTime(a, memberId, calendar.getTime()); // Child increases the effective time by one day
merge(branchPath, a, "Rebased effective time change over update").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.MEMBER, memberId).statusCode(200)
.body("released", equalTo(true))
.body("effectiveTime", nullValue())
.body("active", equalTo(false));
getComponent(a, SnomedComponentType.MEMBER, memberId).statusCode(200)
.body("released", equalTo(true))
.body("effectiveTime", nullValue()) // Parent wins because of the effective time unset
.body("active", equalTo(false)); // Child didn't update the status, so inactivation on the parent is in effect
}
@Ignore
@Test
public void rebaseConceptDeletionOverNewOutboundRelationships() throws Exception {
// new concept on test branch
final String deletedConcept = createNewConcept(branchPath);
// new child branch of test parent branch
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
// create a new outbound relationship
final String newOutboundRelationshipFromDeletedConcept = createNewRelationship(branchPath, deletedConcept, Concepts.FINDING_SITE, Concepts.ROOT_CONCEPT, Concepts.INFERRED_RELATIONSHIP);
// delete destination concept on child branch
deleteComponent(a, SnomedComponentType.CONCEPT, deletedConcept, false);
// rebase child branch with deletion over new relationship, this should succeed, but should also implicitly delete the relationship
merge(branchPath, a, "Rebased concept deletion over new outbound relationship").body("status", equalTo(Merge.Status.CONFLICTS.name()));
merge(branchPath, a, "Rebased concept deletion over new outbound relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// relationships should be deleted along with the already deleted destination concept
getComponent(a, SnomedComponentType.RELATIONSHIP, newOutboundRelationshipFromDeletedConcept).statusCode(404);
}
@Test
public void rebaseConceptDeletionOverNewInboundRelationships() throws Exception {
// new concept on test branch
final String deletedConcept = createNewConcept(branchPath);
// new child branch of test parent branch
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
// create a new relationship to newly created destination concept on parent branch
final String newInboundRelationshipToDeletedConcept = createNewRelationship(branchPath, Concepts.ROOT_CONCEPT, Concepts.FINDING_SITE, deletedConcept, Concepts.INFERRED_RELATIONSHIP);
// delete destination concept on child branch
deleteComponent(a, SnomedComponentType.CONCEPT, deletedConcept, false);
// rebase child branch with deletion over new relationship, this should succeed, but should also implicitly delete the relationship
merge(branchPath, a, "Rebased concept deletion over new inbound relationship").body("status", equalTo(Merge.Status.CONFLICTS.name()));
// relationships should be deleted along with the already deleted destination concept
getComponent(a, SnomedComponentType.RELATIONSHIP, newInboundRelationshipToDeletedConcept).statusCode(404);
}
@Test
public void rebaseConceptDeletionOverNewOutAndInboundRelationships() throws Exception {
// new concept on test branch
final String deletedConcept = createNewConcept(branchPath);
// new child branch of test parent branch
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
// create a new relationship to newly created destination concept on parent branch
final String newInboundRelationshipToDeletedConcept = createNewRelationship(branchPath, Concepts.ROOT_CONCEPT, Concepts.FINDING_SITE, deletedConcept, Concepts.INFERRED_RELATIONSHIP);
final String newOutboundRelationshipFromDeletedConcept = createNewRelationship(branchPath, deletedConcept, Concepts.FINDING_SITE, Concepts.ROOT_CONCEPT, Concepts.INFERRED_RELATIONSHIP);
// delete destination concept on child branch
deleteComponent(a, SnomedComponentType.CONCEPT, deletedConcept, false);
// rebase child branch with deletion over new relationship, this should succeed, but should also implicitly delete the relationship
merge(branchPath, a, "Rebased concept deletion over new outbound and inbound relationships").body("status", equalTo(Merge.Status.CONFLICTS.name()));
// relationships should be deleted along with the already deleted destination concept
getComponent(a, SnomedComponentType.RELATIONSHIP, newOutboundRelationshipFromDeletedConcept).statusCode(404);
getComponent(a, SnomedComponentType.RELATIONSHIP, newInboundRelationshipToDeletedConcept).statusCode(404);
}
@Test
public void mergeThenRebaseOtherTask() throws Exception {
final String conceptA = createNewConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
final IBranchPath b = BranchPathUtils.createPath(branchPath, "b");
branching.createBranch(a).statusCode(201);
branching.createBranch(b).statusCode(201);
Map<?, ?> inactivationRequest = ImmutableMap.builder()
.put("active", false)
.put("inactivationProperties", new InactivationProperties(Concepts.DUPLICATE, List.of(new AssociationTarget(Concepts.REFSET_SAME_AS_ASSOCIATION, Concepts.FULLY_SPECIFIED_NAME))))
.put("commitComment", "Inactivated concept")
.build();
updateComponent(a, SnomedComponentType.CONCEPT, conceptA, inactivationRequest).statusCode(204);
final String conceptB = createNewConcept(b);
merge(a, branchPath, "Merge branch A").body("status", equalTo(Merge.Status.COMPLETED.name()));
SnomedConcept conceptAOnParent = getComponent(branchPath, SnomedComponentType.CONCEPT, conceptA, "members(),relationships()").statusCode(200).extract().as(SnomedConcept.class);
assertThat(conceptAOnParent.getRelationships()).hasSize(1);
assertThat(conceptAOnParent.getMembers()).hasSize(2);
merge(branchPath, b, "Rebase branch B").body("status", equalTo(Merge.Status.COMPLETED.name()));
SnomedConcept conceptAOnBranchB = getComponent(b, SnomedComponentType.CONCEPT, conceptA, "members(),relationships()").statusCode(200).extract().as(SnomedConcept.class);
assertThat(conceptAOnBranchB.getRelationships()).hasSize(1);
assertThat(conceptAOnBranchB.getMembers()).hasSize(2);
getComponent(b, SnomedComponentType.CONCEPT, conceptB, "relationships()").statusCode(200).extract().as(SnomedConcept.class);
}
@Test
public void rebaseDivergedThenMerge() throws Exception {
final IBranchPath task1 = BranchPathUtils.createPath(branchPath, "task1");
branching.createBranch(task1).statusCode(201);
final IBranchPath task2 = BranchPathUtils.createPath(branchPath, "task2");
branching.createBranch(task2).statusCode(201);
final String task1Concept = createNewConcept(task1);
final String task2Concept = createNewConcept(task2);
final String parentConcept = createNewConcept(branchPath);
// Synchronization makes parentConcept visible on task 2
getComponent(task2, SnomedComponentType.CONCEPT, parentConcept).statusCode(404);
merge(branchPath, task2, "Synchronize task 2").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(task2, SnomedComponentType.CONCEPT, parentConcept).statusCode(200);
// Synchronization makes parentConcept visible on task 1
getComponent(task1, SnomedComponentType.CONCEPT, parentConcept).statusCode(404);
merge(branchPath, task1, "Synchronize task 1").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(task1, SnomedComponentType.CONCEPT, parentConcept).statusCode(200);
// Promotion makes task2Concept visible on parent branch
getComponent(branchPath, SnomedComponentType.CONCEPT, task2Concept).statusCode(404);
merge(task2, branchPath, "Promote task 2").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.CONCEPT, task2Concept).statusCode(200);
// Synchronization makes task2Concept (that was just promoted to the parent branch) visible on task 1
getComponent(task1, SnomedComponentType.CONCEPT, task2Concept).statusCode(404);
merge(branchPath, task1, "Synchronize task 1 after promoting task 2").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(task1, SnomedComponentType.CONCEPT, task2Concept).statusCode(200);
// Promotion makes task1Concept visible on parent branch
getComponent(branchPath, SnomedComponentType.CONCEPT, task1Concept).statusCode(404);
merge(task1, branchPath, "Promote task 1").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.CONCEPT, task1Concept).statusCode(200);
}
}
| snomed/com.b2international.snowowl.snomed.core.rest.tests/src/com/b2international/snowowl/snomed/core/rest/branches/SnomedMergeApiTest.java | /*
* Copyright 2011-2020 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.snomed.core.rest.branches;
import static com.b2international.snowowl.snomed.core.rest.CodeSystemVersionRestRequests.getNextAvailableEffectiveDate;
import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.createComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.deleteComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.getComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.updateComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedRefSetRestRequests.updateRefSetComponent;
import static com.b2international.snowowl.snomed.core.rest.SnomedRefSetRestRequests.updateRefSetMemberEffectiveTime;
import static com.b2international.snowowl.snomed.core.rest.SnomedRestFixtures.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertFalse;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.b2international.commons.exceptions.BadRequestException;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.branch.BranchPathUtils;
import com.b2international.snowowl.core.date.DateFormats;
import com.b2international.snowowl.core.date.EffectiveTimes;
import com.b2international.snowowl.core.merge.Merge;
import com.b2international.snowowl.snomed.common.SnomedConstants.Concepts;
import com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants;
import com.b2international.snowowl.snomed.core.domain.Acceptability;
import com.b2international.snowowl.snomed.core.domain.AssociationTarget;
import com.b2international.snowowl.snomed.core.domain.InactivationProperties;
import com.b2international.snowowl.snomed.core.domain.SnomedConcept;
import com.b2international.snowowl.snomed.core.rest.AbstractSnomedApiTest;
import com.b2international.snowowl.snomed.core.rest.SnomedComponentType;
import com.google.common.collect.ImmutableMap;
/**
* Contains test cases for the branch rebase and merge functionality.
* <p>
* All scenarios that result in a content conflict should be placed in {@link SnomedMergeConflictTest} instead.
*
* @since 2.0
*/
public class SnomedMergeApiTest extends AbstractSnomedApiTest {
private static void rebaseConceptDeletionOverChange(IBranchPath parentPath, IBranchPath childPath, String conceptId) {
final Map<?, ?> changeOnParent = ImmutableMap.builder()
.put("definitionStatusId", Concepts.FULLY_DEFINED)
.put("commitComment", "Changed definition status on parent")
.build();
updateComponent(parentPath, SnomedComponentType.CONCEPT, conceptId, changeOnParent).statusCode(204);
deleteComponent(childPath, SnomedComponentType.CONCEPT, conceptId, false).statusCode(204);
merge(parentPath, childPath, "Rebased concept deletion over concept change").body("status", equalTo(Merge.Status.COMPLETED.name()));
}
@Test
public void mergeNewConceptForward() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String conceptId = createNewConcept(a);
merge(a, branchPath, "Merged new concept from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.CONCEPT, conceptId).statusCode(200);
getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(200);
}
@Test
public void mergeNewConceptForwardWithChildBranchDelete() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String conceptId = createNewConcept(a);
merge(a, branchPath, "Merged new concept from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
branching.deleteBranch(a).statusCode(204);
// getComponent(a, SnomedComponentType.CONCEPT, conceptId).statusCode(404);
SnomedConcept concept = getConcept(conceptId, "descriptions(),relationships()");
assertFalse(concept.getDescriptions().isEmpty());
assertFalse(concept.getRelationships().isEmpty());
}
@Test
public void mergeNewDescriptionForward() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String descriptionId = createNewDescription(a);
merge(a, branchPath, "Merged new description from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
getComponent(branchPath, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
}
@Test
public void mergeNewRelationshipForward() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
String relationshipId = createNewRelationship(a);
merge(a, branchPath, "Merged new relationship from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
}
@Test
public void noMergeWithNonExistentReview() throws BadRequestException {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
createNewConcept(a);
merge(a, branchPath, "Merged new concept from child branch with non-existent review ID", "non-existent-id")
.body("status", equalTo(Merge.Status.FAILED.name()));
}
// @Test
// public void noMergeNewConceptDiverged() {
// final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
// createBranch(a).statusCode(201);
//
// final String concept1Id = createNewConcept(a);
// final String concept2Id = createNewConcept(branchPath);
//
// getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(404);
// getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
// getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
//
// merge(a, branchPath, "Merged new concept from diverged branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
//
// getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(404);
// getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
// getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
// }
// @Test
// public void noMergeNewDescriptionDiverged() {
// IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
// createBranch(a).statusCode(201);
//
// String description1Id = createNewDescription(a);
// String description2Id = createNewDescription(branchPath);
//
// getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
// getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
// getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(404);
//
// merge(a, branchPath, "Merged new description from diverged branch").body("status", equalTo(Merge.Status.FAILED.name()));
//
// getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
// getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
// getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(404);
// }
// @Test
// public void noMergeNewRelationshipDiverged() {
// IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
// createBranch(a).statusCode(201);
//
// String relationship1Id = createNewRelationship(a);
// String relationship2Id = createNewRelationship(branchPath);
//
// getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(404);
// getComponent(a, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(200);
// getComponent(a, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(404);
//
// merge(a, branchPath, "Merged new relationship from diverged branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
//
// getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(404);
// getComponent(a, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
//
// getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(200);
// getComponent(a, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(404);
// }
@Test
public void mergeNewConceptToUnrelatedBranch() {
final IBranchPath v1 = BranchPathUtils.createPath(branchPath, "v1");
branching.createBranch(v1).statusCode(201);
// Concept 1 is created on the two branches' common ancestor
final String concept1Id = createNewConcept(branchPath);
final IBranchPath v2 = BranchPathUtils.createPath(branchPath, "v2");
branching.createBranch(v2).statusCode(201);
final IBranchPath a = BranchPathUtils.createPath(v1, "extension-old");
branching.createBranch(a).statusCode(201);
final IBranchPath b = BranchPathUtils.createPath(v2, "extension-new");
branching.createBranch(b).statusCode(201);
// Concept 2 is initially only visible on branch "extension-old"
final String concept2Id = createNewConcept(a);
getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(404);
getComponent(b, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
merge(a, b, "Merged new concept from unrelated branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(b, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
getComponent(b, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
}
@Test
public void mergeNewDescriptionToUnrelatedBranch() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final IBranchPath b = BranchPathUtils.createPath(branchPath, "b");
branching.createBranch(b).statusCode(201);
final String descriptionId = createNewDescription(a);
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
merge(a, b, "Merged new description from unrelated branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200);
}
@Test
public void mergeNewRelationshipToUnrelatedBranch() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final IBranchPath b = BranchPathUtils.createPath(branchPath, "b");
branching.createBranch(b).statusCode(201);
final String relationshipId = createNewRelationship(a);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(404);
merge(a, b, "Merged new relationship from unrelated branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
}
@Test
public void mergeReactivatedConcept() {
final String conceptId = createInactiveConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
reactivateConcept(a, conceptId);
merge(a, branchPath, "Merged reactivation from child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId, "descriptions()", "relationships()").statusCode(200)
.body("active", equalTo(true))
.body("descriptions.items[0].active", equalTo(true))
.body("descriptions.items[1].active", equalTo(true))
// TODO check removal of CONCEPT_NON_CURRENT
.body("relationships.items[0].active", equalTo(true));
}
@Test
public void rebaseReactivatedConcept() {
final String concept1Id = createInactiveConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
reactivateConcept(a, concept1Id);
// Create concept 2 on "branchPath" so that "a" can be rebased
final String concept2Id = createNewConcept(branchPath);
merge(branchPath, a, "Rebased reactivation on child branch").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Concept 1 should be active on "a", but still inactive on "branchPath"
getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id, "descriptions()", "relationships()").statusCode(200)
.body("active", equalTo(false))
.body("descriptions.items[0].active", equalTo(true))
.body("descriptions.items[1].active", equalTo(true))
.body("relationships.items[0].active", equalTo(false));
getComponent(a, SnomedComponentType.CONCEPT, concept1Id, "descriptions()", "relationships()").statusCode(200)
.body("active", equalTo(true))
.body("descriptions.items[0].active", equalTo(true))
.body("descriptions.items[1].active", equalTo(true))
.body("relationships.items[0].active", equalTo(true));
// Concept 2 should be visible everywhere
getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
}
@Test
public void rebaseNewConceptDiverged() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String concept1Id = createNewConcept(branchPath);
final String concept2Id = createNewConcept(a);
getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(404);
getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
merge(branchPath, a, "Rebased new concept").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Concept 1 from the parent becomes visible on the child after rebasing
getComponent(branchPath, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
// Concept 2 should still not be present on the parent, however
getComponent(branchPath, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
getComponent(a, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
}
@Test
public void rebaseNewDescriptionDiverged() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String description1Id = createNewDescription(branchPath);
final String description2Id = createNewDescription(a);
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
merge(branchPath, a, "Rebased new description").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Description 1 from the parent becomes visible on the child after rebasing
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200);
// Description 2 should still not be present on the parent, however
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
}
@Test
public void rebaseNewRelationshipDiverged() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String relationship1Id = createNewRelationship(branchPath);
final String relationship2Id = createNewRelationship(a);
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(404);
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(404);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(200);
merge(branchPath, a, "Rebased new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Relationship 1 from the parent becomes visible on the child after rebasing
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationship1Id).statusCode(200);
// Relationship 2 should still not be present on the parent, however
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(404);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationship2Id).statusCode(200);
}
@Test
public void rebaseNewConceptStale() {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final IBranchPath b = BranchPathUtils.createPath(a, "b");
branching.createBranch(b).statusCode(201);
final String concept1Id = createNewConcept(b);
final String concept2Id = createNewConcept(a);
final String concept3Id = createNewConcept(branchPath);
merge(branchPath, a, "Rebased new concept on child over new concept on parent").body("status", equalTo(Merge.Status.COMPLETED.name()));
// "a" now knows about concept 3
getComponent(branchPath, SnomedComponentType.CONCEPT, concept3Id).statusCode(200);
getComponent(a, SnomedComponentType.CONCEPT, concept3Id).statusCode(200);
// "b" is now in STALE state, and doesn't know about either concept 2 or 3
getComponent(b, SnomedComponentType.CONCEPT, concept3Id).statusCode(404);
getComponent(b, SnomedComponentType.CONCEPT, concept2Id).statusCode(404);
merge(a, b, "Rebased new concept on nested child over new concepts on child").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Now "b" should see all three concepts
getComponent(b, SnomedComponentType.CONCEPT, concept3Id).statusCode(200);
getComponent(b, SnomedComponentType.CONCEPT, concept2Id).statusCode(200);
getComponent(b, SnomedComponentType.CONCEPT, concept1Id).statusCode(200);
}
@Test
public void rebaseChangedConceptOnParentDeletedOnBranch() {
final String conceptId = createNewConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
rebaseConceptDeletionOverChange(branchPath, a, conceptId);
// Concept should still be present on parent, and deleted on child
getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(200).body("definitionStatusId", equalTo(Concepts.FULLY_DEFINED));
getComponent(a, SnomedComponentType.CONCEPT, conceptId).statusCode(404);
}
@Test
public void rebaseChangedDescriptionOnParentDeletedOnBranch() {
final String descriptionId = createNewDescription(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
changeCaseSignificance(branchPath, descriptionId); // Parent branch changes to CaseSignificance.ENTIRE_TERM_CASE_SENSITIVE
deleteComponent(a, SnomedComponentType.DESCRIPTION, descriptionId, false).statusCode(204);
merge(branchPath, a, "Rebased deletion over case significance change").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200).body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_SENSITIVE));
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
}
@Test
public void rebaseAndMergeChangedOnParentDeletedOnBranch() {
final String conceptId = createNewConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
rebaseConceptDeletionOverChange(branchPath, a, conceptId);
merge(a, branchPath, "Merged concept deletion").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Concept should now be deleted everywhere
getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(404);
getComponent(a, SnomedComponentType.CONCEPT, conceptId).statusCode(404);
}
@Test
public void rebaseAndMergeChangedDescription() {
final String description1Id = createNewDescription(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String description2Id = createNewDescription(branchPath);
final Map<?, ?> requestBody = ImmutableMap.builder()
.put("caseSignificanceId", Concepts.ENTIRE_TERM_CASE_INSENSITIVE)
.put("moduleId", Concepts.MODULE_ROOT)
.put("commitComment", "Changed case significance and module on child")
.build();
updateComponent(a, SnomedComponentType.DESCRIPTION, description1Id, requestBody);
merge(branchPath, a, "Rebased description change over new description creation").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Description 2 is now visible on both parent and child
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
// Description 1 retains the changes on child, keeps the original values on parent
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ONLY_INITIAL_CHARACTER_CASE_INSENSITIVE))
.body("moduleId", equalTo(Concepts.MODULE_SCT_CORE));
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_INSENSITIVE))
.body("moduleId", equalTo(Concepts.MODULE_ROOT));
merge(a, branchPath, "Merged description change to parent").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
// Description 1 changes are visible everywhere
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_INSENSITIVE))
.body("moduleId", equalTo(Concepts.MODULE_ROOT));
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_INSENSITIVE))
.body("moduleId", equalTo(Concepts.MODULE_ROOT));
}
@Test
public void rebaseAndMergeNewDescriptionBothDeleted() {
final String description1Id = createNewDescription(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String description2Id = createNewDescription(branchPath);
deleteComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id, false).statusCode(204);
deleteComponent(a, SnomedComponentType.DESCRIPTION, description1Id, false).statusCode(204);
/*
* The rebase sees that the same thing has already happened on the parent branch, and does not
* add an empty commit to the new instance of the child; it will be in UP_TO_DATE state and can
* not be promoted.
*/
merge(branchPath, a, "Rebased description dual deletion over description creation").body("status", equalTo(Merge.Status.COMPLETED.name()));
merge(a, branchPath, "Merged description dual deletion").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Description 1 is now deleted on both branches
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, description1Id).statusCode(404);
// Description 2 should be present, however
getComponent(branchPath, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
getComponent(a, SnomedComponentType.DESCRIPTION, description2Id).statusCode(200);
}
@Test
public void rebaseOverReusedRelationshipId() {
final String relationshipId = createNewRelationship(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
deleteComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId, false).statusCode(204);
final Map<?, ?> requestBody = ImmutableMap.builder()
.put("sourceId", Concepts.ROOT_CONCEPT)
.put("moduleId", Concepts.MODULE_SCT_CORE)
.put("typeId", Concepts.FINDING_SITE)
.put("destinationId", Concepts.ROOT_CONCEPT)
.put("id", relationshipId)
.put("commitComment", "Created new relationship on parent with same SCTID")
.build();
createComponent(branchPath, SnomedComponentType.RELATIONSHIP, requestBody).statusCode(201);
// Different relationships before rebase
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("typeId", equalTo(Concepts.FINDING_SITE));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("typeId", equalTo(Concepts.PART_OF));
merge(branchPath, a, "Rebase after new relationship creation on parent").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Same relationships after rebase
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("typeId", equalTo(Concepts.FINDING_SITE));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("typeId", equalTo(Concepts.FINDING_SITE));
}
@Test
public void rebaseTextDefinitions() throws Exception {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
// Create two new text definitions with "cross-shaped" acceptability on child
final String textDefinition1Id = createNewTextDefinition(a, ImmutableMap.of(Concepts.REFSET_LANGUAGE_TYPE_UK, Acceptability.PREFERRED, Concepts.REFSET_LANGUAGE_TYPE_US, Acceptability.ACCEPTABLE));
final String textDefinition2Id = createNewTextDefinition(a, ImmutableMap.of(Concepts.REFSET_LANGUAGE_TYPE_UK, Acceptability.ACCEPTABLE, Concepts.REFSET_LANGUAGE_TYPE_US, Acceptability.PREFERRED));
// Create change on parent
final String relationshipId = createNewRelationship(branchPath);
merge(branchPath, a, "Rebased new text definitions over new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Relationship should be visible on both branches
getComponent(branchPath, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200);
// Text definitions are only on the child, however
getComponent(branchPath, SnomedComponentType.DESCRIPTION, textDefinition1Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, textDefinition1Id).statusCode(200);
getComponent(branchPath, SnomedComponentType.DESCRIPTION, textDefinition2Id).statusCode(404);
getComponent(a, SnomedComponentType.DESCRIPTION, textDefinition2Id).statusCode(200);
}
@Test
public void rebaseStaleBranchWithChangesOnDeletedContent() throws Exception {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String relationshipId = createNewRelationship(a);
final String descriptionId = createNewDescription(a);
final IBranchPath b = BranchPathUtils.createPath(a, "b");
branching.createBranch(b).statusCode(201);
deleteComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId, false).statusCode(204);
deleteComponent(a, SnomedComponentType.DESCRIPTION, descriptionId, false).statusCode(204);
changeCaseSignificance(b, descriptionId);
changeRelationshipGroup(b, relationshipId);
// Make change on "branchPath" so "a" can be rebased
createNewRelationship(branchPath);
merge(branchPath, a, "Rebased component deletion over new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// "b" should be STALE at this point, try to rebase it, it should pass and the components should be deleted
merge(a, b, "Rebased component updates over deletion").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Verify that the two deleted components are really deleted
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(404);
}
@Test
public void rebaseStaleBranchWithChangesOnNewContent() throws Exception {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String relationshipId = createNewRelationship(a);
final String descriptionId = createNewDescription(a);
final IBranchPath b = BranchPathUtils.createPath(a, "b");
branching.createBranch(b).statusCode(201);
changeCaseSignificance(b, descriptionId);
changeRelationshipGroup(b, relationshipId);
// Make change on "branchPath" so "a" can be rebased
createNewRelationship(branchPath);
merge(branchPath, a, "Rebased new components over new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(a, SnomedComponentType.DESCRIPTION, descriptionId)
.statusCode(200)
.body("caseSignificanceId", equalTo(Concepts.ONLY_INITIAL_CHARACTER_CASE_INSENSITIVE));
getComponent(a, SnomedComponentType.RELATIONSHIP, relationshipId)
.statusCode(200)
.body("group", equalTo(0));
// "b" should be STALE at this point, try to rebase it, it should pass and the components should still exist with changed content
merge(a, b, "Rebased changed components over new components").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Verify that the two components have the modified values
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(200).body("caseSignificanceId", equalTo(Concepts.ENTIRE_TERM_CASE_SENSITIVE));
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("group", equalTo(99));
}
@Test
public void rebaseStaleBranchWithDeleteOnChangedContent() throws Exception {
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final String relationshipId = createNewRelationship(a);
final String descriptionId = createNewDescription(a);
final IBranchPath b = BranchPathUtils.createPath(a, "b");
branching.createBranch(b).statusCode(201);
// Make changes on branch "a"
changeCaseSignificance(a, descriptionId);
changeRelationshipGroup(a, relationshipId);
// Delete description on branch "b"
deleteComponent(b, SnomedComponentType.DESCRIPTION, descriptionId, false).statusCode(204);
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
// Make change on "branchPath" so "a" can be rebased
createNewRelationship(branchPath);
merge(branchPath, a, "Rebased changed components over new relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// "b" should be STALE at this point, try to rebase it, it should pass and the description should be deleted
merge(a, b, "Rebased description deletion over changed components").body("status", equalTo(Merge.Status.COMPLETED.name()));
// Verify that the relationship has the modified values, and the description stayed deleted
getComponent(b, SnomedComponentType.DESCRIPTION, descriptionId).statusCode(404);
getComponent(b, SnomedComponentType.RELATIONSHIP, relationshipId).statusCode(200).body("group", equalTo(99));
}
@Test
@Ignore("Currently always fails due to merge policy")
public void rebaseChangedConceptOnBranchDeletedOnParent() {
final String conceptId = createNewConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final Map<?, ?> requestBody = ImmutableMap.builder()
.put("definitionStatusId", Concepts.FULLY_DEFINED)
.put("commitComment", "Changed definition status on child")
.build();
updateComponent(a, SnomedComponentType.CONCEPT, conceptId, requestBody).statusCode(204);
deleteComponent(branchPath, SnomedComponentType.CONCEPT, conceptId, false).statusCode(204);
merge(branchPath, a, "Rebased concept change over deletion").body("status", equalTo(Merge.Status.COMPLETED.name()));
}
@Test
public void rebaseUnsetEffectiveTimeOnSource() {
final String memberId = createNewRefSetMember(branchPath);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(getNextAvailableEffectiveDate(SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME));
updateRefSetMemberEffectiveTime(branchPath, memberId, calendar.getTime());
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
calendar.add(Calendar.DATE, 1);
updateRefSetMemberEffectiveTime(branchPath, memberId, calendar.getTime()); // Parent increases the effective time by one day
final Map<?, ?> childRequest = ImmutableMap.builder()
.put("active", false)
.put("commitComment", "Inactivated reference set member")
.build();
updateRefSetComponent(a, SnomedComponentType.MEMBER, memberId, childRequest, false).statusCode(204); // Child unsets it and inactivates the member
merge(branchPath, a, "Rebased update over effective time change").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.MEMBER, memberId).statusCode(200)
.body("released", equalTo(true))
.body("effectiveTime", equalTo(EffectiveTimes.format(calendar.getTime(), DateFormats.SHORT)))
.body("active", equalTo(true));
getComponent(a, SnomedComponentType.MEMBER, memberId).statusCode(200)
.body("released", equalTo(true))
.body("effectiveTime", nullValue())
.body("active", equalTo(false));
}
@Test
public void rebaseUnsetEffectiveTimeOnTarget() {
final String memberId = createNewRefSetMember(branchPath);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(getNextAvailableEffectiveDate(SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME));
updateRefSetMemberEffectiveTime(branchPath, memberId, calendar.getTime());
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
final Map<?, ?> parentRequest = ImmutableMap.builder()
.put("active", false)
.put("commitComment", "Inactivated reference set member")
.build();
updateRefSetComponent(branchPath, SnomedComponentType.MEMBER, memberId, parentRequest, false).statusCode(204); // Parent unsets the effective time and inactivates the member
calendar.add(Calendar.DATE, 1);
updateRefSetMemberEffectiveTime(a, memberId, calendar.getTime()); // Child increases the effective time by one day
merge(branchPath, a, "Rebased effective time change over update").body("status", equalTo(Merge.Status.COMPLETED.name()));
getComponent(branchPath, SnomedComponentType.MEMBER, memberId).statusCode(200)
.body("released", equalTo(true))
.body("effectiveTime", nullValue())
.body("active", equalTo(false));
getComponent(a, SnomedComponentType.MEMBER, memberId).statusCode(200)
.body("released", equalTo(true))
.body("effectiveTime", nullValue()) // Parent wins because of the effective time unset
.body("active", equalTo(false)); // Child didn't update the status, so inactivation on the parent is in effect
}
@Ignore
@Test
public void rebaseConceptDeletionOverNewOutboundRelationships() throws Exception {
// new concept on test branch
final String deletedConcept = createNewConcept(branchPath);
// new child branch of test parent branch
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
// create a new outbound relationship
final String newOutboundRelationshipFromDeletedConcept = createNewRelationship(branchPath, deletedConcept, Concepts.FINDING_SITE, Concepts.ROOT_CONCEPT, Concepts.INFERRED_RELATIONSHIP);
// delete destination concept on child branch
deleteComponent(a, SnomedComponentType.CONCEPT, deletedConcept, false);
// rebase child branch with deletion over new relationship, this should succeed, but should also implicitly delete the relationship
merge(branchPath, a, "Rebased concept deletion over new outbound relationship").body("status", equalTo(Merge.Status.CONFLICTS.name()));
merge(branchPath, a, "Rebased concept deletion over new outbound relationship").body("status", equalTo(Merge.Status.COMPLETED.name()));
// relationships should be deleted along with the already deleted destination concept
getComponent(a, SnomedComponentType.RELATIONSHIP, newOutboundRelationshipFromDeletedConcept).statusCode(404);
}
@Test
public void rebaseConceptDeletionOverNewInboundRelationships() throws Exception {
// new concept on test branch
final String deletedConcept = createNewConcept(branchPath);
// new child branch of test parent branch
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
// create a new relationship to newly created destination concept on parent branch
final String newInboundRelationshipToDeletedConcept = createNewRelationship(branchPath, Concepts.ROOT_CONCEPT, Concepts.FINDING_SITE, deletedConcept, Concepts.INFERRED_RELATIONSHIP);
// delete destination concept on child branch
deleteComponent(a, SnomedComponentType.CONCEPT, deletedConcept, false);
// rebase child branch with deletion over new relationship, this should succeed, but should also implicitly delete the relationship
merge(branchPath, a, "Rebased concept deletion over new inbound relationship").body("status", equalTo(Merge.Status.CONFLICTS.name()));
// relationships should be deleted along with the already deleted destination concept
getComponent(a, SnomedComponentType.RELATIONSHIP, newInboundRelationshipToDeletedConcept).statusCode(404);
}
@Test
public void rebaseConceptDeletionOverNewOutAndInboundRelationships() throws Exception {
// new concept on test branch
final String deletedConcept = createNewConcept(branchPath);
// new child branch of test parent branch
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
branching.createBranch(a).statusCode(201);
// create a new relationship to newly created destination concept on parent branch
final String newInboundRelationshipToDeletedConcept = createNewRelationship(branchPath, Concepts.ROOT_CONCEPT, Concepts.FINDING_SITE, deletedConcept, Concepts.INFERRED_RELATIONSHIP);
final String newOutboundRelationshipFromDeletedConcept = createNewRelationship(branchPath, deletedConcept, Concepts.FINDING_SITE, Concepts.ROOT_CONCEPT, Concepts.INFERRED_RELATIONSHIP);
// delete destination concept on child branch
deleteComponent(a, SnomedComponentType.CONCEPT, deletedConcept, false);
// rebase child branch with deletion over new relationship, this should succeed, but should also implicitly delete the relationship
merge(branchPath, a, "Rebased concept deletion over new outbound and inbound relationships").body("status", equalTo(Merge.Status.CONFLICTS.name()));
// relationships should be deleted along with the already deleted destination concept
getComponent(a, SnomedComponentType.RELATIONSHIP, newOutboundRelationshipFromDeletedConcept).statusCode(404);
getComponent(a, SnomedComponentType.RELATIONSHIP, newInboundRelationshipToDeletedConcept).statusCode(404);
}
@Test
public void mergeThenRebaseOtherTask() throws Exception {
final String conceptA = createNewConcept(branchPath);
final IBranchPath a = BranchPathUtils.createPath(branchPath, "a");
final IBranchPath b = BranchPathUtils.createPath(branchPath, "b");
branching.createBranch(a).statusCode(201);
branching.createBranch(b).statusCode(201);
Map<?, ?> inactivationRequest = ImmutableMap.builder()
.put("active", false)
.put("inactivationProperties", new InactivationProperties(Concepts.DUPLICATE, List.of(new AssociationTarget(Concepts.REFSET_SAME_AS_ASSOCIATION, Concepts.FULLY_SPECIFIED_NAME))))
.put("commitComment", "Inactivated concept")
.build();
updateComponent(a, SnomedComponentType.CONCEPT, conceptA, inactivationRequest).statusCode(204);
final String conceptB = createNewConcept(b);
merge(a, branchPath, "Merge branch A").body("status", equalTo(Merge.Status.COMPLETED.name()));
SnomedConcept conceptAOnParent = getComponent(branchPath, SnomedComponentType.CONCEPT, conceptA, "members(),relationships()").statusCode(200).extract().as(SnomedConcept.class);
assertThat(conceptAOnParent.getRelationships()).hasSize(1);
assertThat(conceptAOnParent.getMembers()).hasSize(2);
merge(branchPath, b, "Rebase branch B").body("status", equalTo(Merge.Status.COMPLETED.name()));
SnomedConcept conceptAOnBranchB = getComponent(b, SnomedComponentType.CONCEPT, conceptA, "members(),relationships()").statusCode(200).extract().as(SnomedConcept.class);
assertThat(conceptAOnBranchB.getRelationships()).hasSize(1);
assertThat(conceptAOnBranchB.getMembers()).hasSize(2);
getComponent(b, SnomedComponentType.CONCEPT, conceptB, "relationships()").statusCode(200).extract().as(SnomedConcept.class);
}
}
| [snomed] Add test case for rebase-then-merge scenario | snomed/com.b2international.snowowl.snomed.core.rest.tests/src/com/b2international/snowowl/snomed/core/rest/branches/SnomedMergeApiTest.java | [snomed] Add test case for rebase-then-merge scenario | <ide><path>nomed/com.b2international.snowowl.snomed.core.rest.tests/src/com/b2international/snowowl/snomed/core/rest/branches/SnomedMergeApiTest.java
<ide>
<ide> getComponent(b, SnomedComponentType.CONCEPT, conceptB, "relationships()").statusCode(200).extract().as(SnomedConcept.class);
<ide> }
<del>
<add>
<add> @Test
<add> public void rebaseDivergedThenMerge() throws Exception {
<add> final IBranchPath task1 = BranchPathUtils.createPath(branchPath, "task1");
<add> branching.createBranch(task1).statusCode(201);
<add>
<add> final IBranchPath task2 = BranchPathUtils.createPath(branchPath, "task2");
<add> branching.createBranch(task2).statusCode(201);
<add>
<add> final String task1Concept = createNewConcept(task1);
<add> final String task2Concept = createNewConcept(task2);
<add> final String parentConcept = createNewConcept(branchPath);
<add>
<add> // Synchronization makes parentConcept visible on task 2
<add> getComponent(task2, SnomedComponentType.CONCEPT, parentConcept).statusCode(404);
<add> merge(branchPath, task2, "Synchronize task 2").body("status", equalTo(Merge.Status.COMPLETED.name()));
<add> getComponent(task2, SnomedComponentType.CONCEPT, parentConcept).statusCode(200);
<add>
<add> // Synchronization makes parentConcept visible on task 1
<add> getComponent(task1, SnomedComponentType.CONCEPT, parentConcept).statusCode(404);
<add> merge(branchPath, task1, "Synchronize task 1").body("status", equalTo(Merge.Status.COMPLETED.name()));
<add> getComponent(task1, SnomedComponentType.CONCEPT, parentConcept).statusCode(200);
<add>
<add> // Promotion makes task2Concept visible on parent branch
<add> getComponent(branchPath, SnomedComponentType.CONCEPT, task2Concept).statusCode(404);
<add> merge(task2, branchPath, "Promote task 2").body("status", equalTo(Merge.Status.COMPLETED.name()));
<add> getComponent(branchPath, SnomedComponentType.CONCEPT, task2Concept).statusCode(200);
<add>
<add> // Synchronization makes task2Concept (that was just promoted to the parent branch) visible on task 1
<add> getComponent(task1, SnomedComponentType.CONCEPT, task2Concept).statusCode(404);
<add> merge(branchPath, task1, "Synchronize task 1 after promoting task 2").body("status", equalTo(Merge.Status.COMPLETED.name()));
<add> getComponent(task1, SnomedComponentType.CONCEPT, task2Concept).statusCode(200);
<add>
<add> // Promotion makes task1Concept visible on parent branch
<add> getComponent(branchPath, SnomedComponentType.CONCEPT, task1Concept).statusCode(404);
<add> merge(task1, branchPath, "Promote task 1").body("status", equalTo(Merge.Status.COMPLETED.name()));
<add> getComponent(branchPath, SnomedComponentType.CONCEPT, task1Concept).statusCode(200);
<add> }
<ide> } |
|
Java | lgpl-2.1 | d2e7e573d1c2ef94b244f824f00734e0d462494d | 0 | CreativeMD/LittleTiles | package com.creativemd.littletiles.common.tiles.vec;
import com.creativemd.littletiles.common.utils.grid.LittleGridContext;
import net.minecraft.util.math.BlockPos;
public class LittleAbsoluteBox {
public BlockPos pos;
public LittleGridContext context;
public LittleTileBox box;
public LittleAbsoluteBox(BlockPos pos) {
this.pos = pos;
this.context = LittleGridContext.getMin();
this.box = new LittleTileBox(0, 0, 0, context.size, context.size, context.size);
}
public LittleAbsoluteBox(BlockPos pos, LittleTileBox box, LittleGridContext context) {
this.pos = pos;
this.box = box;
this.context = context;
}
public void convertTo(LittleGridContext to) {
box.convertTo(this.context, to);
this.context = to;
}
public void convertToSmallest() {
int size = box.getSmallestContext(context);
if (size < context.size)
convertTo(LittleGridContext.get(size));
}
public LittleTileVec getDoubledCenter(BlockPos pos) {
LittleTileVec vec = box.getCenter();
vec.add(this.pos.subtract(pos), context);
vec.scale(2);
return vec;
}
}
| src/main/java/com/creativemd/littletiles/common/tiles/vec/LittleAbsoluteBox.java | package com.creativemd.littletiles.common.tiles.vec;
import com.creativemd.littletiles.common.utils.grid.LittleGridContext;
import net.minecraft.util.math.BlockPos;
public class LittleAbsoluteBox {
public BlockPos pos;
public LittleGridContext context;
public LittleTileBox box;
public void convertTo(LittleGridContext to) {
box.convertTo(this.context, to);
this.context = to;
}
public void convertToSmallest() {
int size = box.getSmallestContext(context);
if (size < context.size)
convertTo(LittleGridContext.get(size));
}
public LittleTileVec getDoubledCenter(BlockPos pos) {
LittleTileVec vec = box.getCenter();
vec.add(this.pos.subtract(pos), context);
vec.scale(2);
return vec;
}
}
| Added constructors to LittleAbsoluteBox
| src/main/java/com/creativemd/littletiles/common/tiles/vec/LittleAbsoluteBox.java | Added constructors to LittleAbsoluteBox | <ide><path>rc/main/java/com/creativemd/littletiles/common/tiles/vec/LittleAbsoluteBox.java
<ide> public BlockPos pos;
<ide> public LittleGridContext context;
<ide> public LittleTileBox box;
<add>
<add> public LittleAbsoluteBox(BlockPos pos) {
<add> this.pos = pos;
<add> this.context = LittleGridContext.getMin();
<add> this.box = new LittleTileBox(0, 0, 0, context.size, context.size, context.size);
<add> }
<add>
<add> public LittleAbsoluteBox(BlockPos pos, LittleTileBox box, LittleGridContext context) {
<add> this.pos = pos;
<add> this.box = box;
<add> this.context = context;
<add> }
<ide>
<ide> public void convertTo(LittleGridContext to) {
<ide> box.convertTo(this.context, to); |
|
JavaScript | mpl-2.0 | 47bb0885b2d1767281de862d2bf7e8fa6e6bc9ab | 0 | jmaher/ouija,dminor/ouija,jmaher/ouija,jmaher/ouija,dminor/ouija,dminor/ouija | $(function() {
$error = $("#error"),
$body = $("body");
//TODO: consider revisiting this to ensure we have accurate data and the right format/presentations
function createDates(data) {
var s = $('<select />');
data.sort;
var count = 0;
var length = 0;
for (var val in data) {
length++;
}
var baseline = 0;
var lastDate = 0;
for(var val in data) {
date = val.split(' ')[0];
count++;
if (count == 1) {
baseline = parseInt(data[val]);
text = date + " (removed: " + baseline + ")";
} else {
text = date + " (changed: " + (parseInt(data[val]) - baseline) + ")";
}
if (count == length) {
$('<option />', {value: val, text:text, selected:'selected'}).appendTo(s);
lastDate = val;
} else {
$('<option />', {value: val, text:text}).appendTo(s);
}
}
toggle = $('<input type="submit" value="Show Optional Jobs" id="toggle" />');
if (!($('select').length)) {
s.appendTo('body');
toggle.appendTo('body');
document.getElementById("toggle").addEventListener("click", toggleState);
} else {
$('select').replaceWith(s);
}
printTable(lastDate);
}
function printTable(date) {
$.getJSON("/data/setadetails/", {date:date}).done(function (data) { getActiveJobs(data, date); });
}
function getActiveJobs(details, date) {
$.getJSON("/data/jobtypes/").done(function (data) { outputTable(data, details, date); });
}
// Simple text replace of full names -> Group-Code format
function printName(testname) {
var retVal = testname.replace(/mochitest-browser-chrome[-]?/, 'M-bc');
retVal = retVal.replace(/mochitest-e10s-browser-chrome[-]?/, 'Me10s-bc');
retVal = retVal.replace(/mochitest-e10s-devtools-chrome[-]?/, 'M-dt');
retVal = retVal.replace('mochitest-e10s', 'Me10s');
retVal = retVal.replace(/mochitest-devtools-chrome[-]?/, 'M-dt');
retVal = retVal.replace('mochitest-other', 'M-oth');
retVal = retVal.replace('mochitest', 'M');
retVal = retVal.replace('crashtest-ipc', 'R-C-ipc');
retVal = retVal.replace('crashtest', 'R-C');
retVal = retVal.replace('jsreftest', 'R-J');
retVal = retVal.replace('reftest-no-accel', 'R-RU');
retVal = retVal.replace('reftest-e10s', 'Re10s-R');
retVal = retVal.replace('reftest', 'R-R');
retVal = retVal.replace('xpcshell', 'O-X');
retVal = retVal.replace('marionette', 'O-Mn');
retVal = retVal.replace('cppunit', 'O-Cpp');
retVal = retVal.replace(/jittest[-]?/, 'O-Jit');
retVal = retVal.replace('web-platform-tests', 'WPT');
return retVal;
}
function fixPlatform(plat) {
retVal = plat.replace('osx10.6', 'osx-10-6');
retVal = retVal.replace('osx10.8', 'osx-10-8');
retVal = retVal.replace('winxp', 'windowsxp');
retVal = retVal.replace('win7', 'windows7-32');
retVal = retVal.replace('win8', 'windows8-64');
return retVal
}
function toggleState() {
item = document.getElementById("toggle");
if (item.value == "Show Optional Jobs") {
fetchData();
item.value = "Hide Optional Jobs";
} else {
fetchData();
item.value = "Show Optional Jobs";
}
}
// determine if we need a strike through or not
// TODO: add features to toggle on off
function jobCode(rawName, partName, osMap) {
item = document.getElementById("toggle");
// Hack: item.value == "Hide Optional Jobs" because of asynchronous behaviour of toggleState(), it should be actually "Show Optional Jobs".
if (item.value == "Hide Optional Jobs") {
if (osMap.indexOf(rawName) >= 0) {
return "<span style='color: grey'>" + partName + " </span>";
}
}
if (!(osMap.indexOf(rawName) >= 0)) {
return "<span style='color: green'><b>" + partName + " </b></span>";
}
}
function buildOSJobMap(joblist) {
var map = {}
for (var i = 0; i < joblist.length; i++) {
var job = joblist[i];
key = fixPlatform(job[0]) + " " + job[1];
if (map[key] === undefined) {
map[key] = [];
}
map[key].push(job[2]);
}
return map;
}
function outputTable(active_jobs, details, date) {
// Get the list of jobs per platform that we don't need to run
var optional_jobs = buildOSJobMap(details['jobtypes'][date]);
// Get a list of all the active jobs on the tree
var active_osjobs = buildOSJobMap(active_jobs['jobtypes']);
var active_oslist = ['linux32 opt', 'linux32 debug',
'linux64 opt', 'linux64 asan', 'linux64 debug',
'osx-10-6 opt', 'osx-10-6 debug',
'osx-10-8 opt', 'osx-10-8 debug',
'windowsxp opt', 'windowsxp debug',
'windows7-32 opt', 'windows7-32 debug',
'windows8-64 opt', 'windows8-64 debug'];
var mytable = $('<table></table>').attr({id:'seta', border: 0});
// Iterate through each OS, add a row and colums
for (var i = 0; i < active_oslist.length; i++) {
var os = active_oslist[i];
var row = $('<tr></tr>').appendTo(mytable);
$('<td></td>').text(os).appendTo(row);
var td_jobs = $('<td></td>').appendTo(row);
var td_div = $('<div style="float: left"></div>').appendTo(td_jobs);
var types = { 'O': {'group': 'O'},
'M': {'group': 'M'}, "Me10s": {'group': 'M-e10s'},
'R': {'group': 'R'}, 'Re10s': {'group': 'R-e10s'},
'WPT': {'group': 'W'}}
for (var type in types) {
types[type]['div'] = $('<span></span>').html('').appendTo(td_div);
}
// Iterate through all jobs for the given OS, find a group and code
active_osjobs[os].sort();
for (var j = 0; j < active_osjobs[os].length; j++) {
var jobparts = printName(active_osjobs[os][j]).split('-', 2);
var group = jobparts[0];
var jobcode = jobparts[1];
if (group in types) {
$('<span></span>').html(jobCode(active_osjobs[os][j], jobcode, optional_jobs[os])).appendTo(types[group]['div']);
} else {
alert("couldn't find matching group: " + group + ", with code: " + jobcode);
}
}
// remove empty groups, add group letter and () for visual grouping
for (var type in types) {
var leftover = types[type]['div'].html().replace(/\<\/span\>/g, '');
leftover = leftover.replace(/\<span\>/g, '');
if (leftover.replace(/ /g, '') == '') {
types[type]['div'].html('');
} else if (type != 'O') {
types[type]['div'].html(types[type]['group'] + '(' + leftover.replace(/\s+$/g, '') + ') ');
}
}
}
if (!($('table').length)) {
mytable.appendTo('body');
} else {
$('table').replaceWith(mytable);
}
}
function gotsummary(data) {
if ($error.is(":visible")) $error.hide();
createDates(data.dates);
}
function fail(error) {
$dates.hide();
$error.text(error).show();
}
function fetchData(e) {
if (e) e.preventDefault();
$.getJSON("/data/setasummary/").done(gotsummary).fail(fail);
}
$(document).on("ajaxStart ajaxStop", function (e) {
(e.type === "ajaxStart") ? $body.addClass("loading") : $body.removeClass("loading");
});
fetchData();
});
| static/js/seta.js | $(function() {
$error = $("#error"),
$body = $("body");
//TODO: consider revisiting this to ensure we have accurate data and the right format/presentations
function createDates(data) {
var s = $('<select />');
data.sort;
var count = 0;
var length = 0;
for (var val in data) {
length++;
}
var baseline = 0;
var lastDate = 0;
for(var val in data) {
date = val.split(' ')[0];
count++;
if (count == 1) {
baseline = parseInt(data[val]);
text = date + " (removed: " + baseline + ")";
} else {
text = date + " (changed: " + (parseInt(data[val]) - baseline) + ")";
}
if (count == length) {
$('<option />', {value: val, text:text, selected:'selected'}).appendTo(s);
lastDate = val;
} else {
$('<option />', {value: val, text:text}).appendTo(s);
}
}
s.appendTo('body');
printTable(lastDate);
}
function printTable(date) {
$.getJSON("/data/setadetails/", {date:date}).done(function (data) { getActiveJobs(data, date); });
}
function getActiveJobs(details, date) {
$.getJSON("/data/jobtypes/").done(function (data) { outputTable(data, details, date); });
}
// Simple text replace of full names -> Group-Code format
function printName(testname) {
var retVal = testname.replace(/mochitest-browser-chrome[-]?/, 'M-bc');
retVal = retVal.replace(/mochitest-e10s-browser-chrome[-]?/, 'Me10s-bc');
retVal = retVal.replace(/mochitest-e10s-devtools-chrome[-]?/, 'M-dt');
retVal = retVal.replace('mochitest-e10s', 'Me10s');
retVal = retVal.replace(/mochitest-devtools-chrome[-]?/, 'M-dt');
retVal = retVal.replace('mochitest-other', 'M-oth');
retVal = retVal.replace('mochitest', 'M');
retVal = retVal.replace('crashtest-ipc', 'R-C-ipc');
retVal = retVal.replace('crashtest', 'R-C');
retVal = retVal.replace('jsreftest', 'R-J');
retVal = retVal.replace('reftest-no-accel', 'R-RU');
retVal = retVal.replace('reftest-e10s', 'Re10s-R');
retVal = retVal.replace('reftest', 'R-R');
retVal = retVal.replace('xpcshell', 'O-X');
retVal = retVal.replace('marionette', 'O-Mn');
retVal = retVal.replace('cppunit', 'O-Cpp');
retVal = retVal.replace(/jittest[-]?/, 'O-Jit');
retVal = retVal.replace('web-platform-tests', 'WPT');
return retVal;
}
function fixPlatform(plat) {
retVal = plat.replace('osx10.6', 'osx-10-6');
retVal = retVal.replace('osx10.8', 'osx-10-8');
retVal = retVal.replace('winxp', 'windowsxp');
retVal = retVal.replace('win7', 'windows7-32');
retVal = retVal.replace('win8', 'windows8-64');
return retVal
}
// determine if we need a strike through or not
// TODO: add features to toggle on off
function jobCode(rawName, partName, osMap) {
if (osMap.indexOf(rawName) >= 0) {
return "<span style='color: grey'>" + partName + " </span>";
} else {
return "<span style='color: green'><b>" + partName + " </b></span>";
}
}
function buildOSJobMap(joblist) {
var map = {}
for (var i = 0; i < joblist.length; i++) {
var job = joblist[i];
key = fixPlatform(job[0]) + " " + job[1];
if (map[key] === undefined) {
map[key] = [];
}
map[key].push(job[2]);
}
return map;
}
function outputTable(active_jobs, details, date) {
// Get the list of jobs per platform that we don't need to run
var optional_jobs = buildOSJobMap(details['jobtypes'][date]);
// Get a list of all the active jobs on the tree
var active_osjobs = buildOSJobMap(active_jobs['jobtypes']);
var active_oslist = ['linux32 opt', 'linux32 debug',
'linux64 opt', 'linux64 asan', 'linux64 debug',
'osx-10-6 opt', 'osx-10-6 debug',
'osx-10-8 opt', 'osx-10-8 debug',
'windowsxp opt', 'windowsxp debug',
'windows7-32 opt', 'windows7-32 debug',
'windows8-64 opt', 'windows8-64 debug'];
var mytable = $('<table></table>').attr({id:'seta', border: 0});
// Iterate through each OS, add a row and colums
for (var i = 0; i < active_oslist.length; i++) {
var os = active_oslist[i];
var row = $('<tr></tr>').appendTo(mytable);
$('<td></td>').text(os).appendTo(row);
var td_jobs = $('<td></td>').appendTo(row);
var td_div = $('<div style="float: left"></div>').appendTo(td_jobs);
var types = { 'O': {'group': 'O'},
'M': {'group': 'M'}, "Me10s": {'group': 'M-e10s'},
'R': {'group': 'R'}, 'Re10s': {'group': 'R-e10s'},
'WPT': {'group': 'W'}}
for (var type in types) {
types[type]['div'] = $('<span></span>').html('').appendTo(td_div);
}
// Iterate through all jobs for the given OS, find a group and code
active_osjobs[os].sort();
for (var j = 0; j < active_osjobs[os].length; j++) {
var jobparts = printName(active_osjobs[os][j]).split('-', 2);
var group = jobparts[0];
var jobcode = jobparts[1];
if (group in types) {
$('<span></span>').html(jobCode(active_osjobs[os][j], jobcode, optional_jobs[os])).appendTo(types[group]['div']);
} else {
alert("couldn't find matching group: " + group + ", with code: " + jobcode);
}
}
// remove empty groups, add group letter and () for visual grouping
for (var type in types) {
var leftover = types[type]['div'].html().replace(/\<\/span\>/g, '');
leftover = leftover.replace(/\<span\>/g, '');
if (leftover.replace(/ /g, '') == '') {
types[type]['div'].html('');
} else if (type != 'O') {
types[type]['div'].html(types[type]['group'] + '(' + leftover.replace(/\s+$/g, '') + ') ');
}
}
}
mytable.appendTo('body');
}
function gotsummary(data) {
if ($error.is(":visible")) $error.hide();
createDates(data.dates);
}
function fail(error) {
$dates.hide();
$error.text(error).show();
}
function fetchData(e) {
if (e) e.preventDefault();
$.getJSON("/data/setasummary/").done(gotsummary).fail(fail);
}
$(document).on("ajaxStart ajaxStop", function (e) {
(e.type === "ajaxStart") ? $body.addClass("loading") : $body.removeClass("loading");
});
fetchData();
});
| Show/Hide functionailty for disabled jobs.
| static/js/seta.js | Show/Hide functionailty for disabled jobs. | <ide><path>tatic/js/seta.js
<ide> $('<option />', {value: val, text:text}).appendTo(s);
<ide> }
<ide> }
<del> s.appendTo('body');
<add> toggle = $('<input type="submit" value="Show Optional Jobs" id="toggle" />');
<add> if (!($('select').length)) {
<add> s.appendTo('body');
<add> toggle.appendTo('body');
<add> document.getElementById("toggle").addEventListener("click", toggleState);
<add> } else {
<add> $('select').replaceWith(s);
<add> }
<ide>
<ide> printTable(lastDate);
<ide> }
<ide> return retVal
<ide> }
<ide>
<add> function toggleState() {
<add> item = document.getElementById("toggle");
<add> if (item.value == "Show Optional Jobs") {
<add> fetchData();
<add> item.value = "Hide Optional Jobs";
<add> } else {
<add> fetchData();
<add> item.value = "Show Optional Jobs";
<add> }
<add> }
<add>
<ide> // determine if we need a strike through or not
<ide> // TODO: add features to toggle on off
<ide> function jobCode(rawName, partName, osMap) {
<del> if (osMap.indexOf(rawName) >= 0) {
<add> item = document.getElementById("toggle");
<add> // Hack: item.value == "Hide Optional Jobs" because of asynchronous behaviour of toggleState(), it should be actually "Show Optional Jobs".
<add> if (item.value == "Hide Optional Jobs") {
<add> if (osMap.indexOf(rawName) >= 0) {
<ide> return "<span style='color: grey'>" + partName + " </span>";
<del> } else {
<del> return "<span style='color: green'><b>" + partName + " </b></span>";
<add> }
<add> }
<add> if (!(osMap.indexOf(rawName) >= 0)) {
<add> return "<span style='color: green'><b>" + partName + " </b></span>";
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> }
<del> mytable.appendTo('body');
<add> if (!($('table').length)) {
<add> mytable.appendTo('body');
<add> } else {
<add> $('table').replaceWith(mytable);
<add> }
<ide> }
<ide>
<ide> function gotsummary(data) { |
|
Java | bsd-3-clause | dbdd626cbb39e5d0520a197936b37b8b0ae098e2 | 0 | NCIP/c3pr,NCIP/c3pr,NCIP/c3pr | package gov.nih.nci.cabig.ctms.client;
import java.io.InputStream;
import java.rmi.RemoteException;
import javax.xml.namespace.QName;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.client.AxisClient;
import org.apache.axis.client.Stub;
import org.apache.axis.configuration.FileProvider;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.axis.types.URI.MalformedURIException;
import org.apache.axis.utils.ClassUtils;
import org.oasis.wsrf.properties.GetResourcePropertyResponse;
import org.globus.gsi.GlobusCredential;
import gov.nih.nci.cabig.ctms.stubs.RegistrationConsumerPortType;
import gov.nih.nci.cabig.ctms.stubs.service.RegistrationConsumerServiceAddressingLocator;
import gov.nih.nci.cabig.ctms.common.RegistrationConsumer;
import gov.nih.nci.cagrid.introduce.security.client.ServiceSecurityClient;
import gov.nih.nci.cagrid.common.Utils;
/**
* This class is autogenerated, DO NOT EDIT GENERATED GRID SERVICE METHODS.
*
* This client is generated automatically by Introduce to provide a clean unwrapped API to the
* service.
*
* On construction the class instance will contact the remote service and retrieve it's security
* metadata description which it will use to configure the Stub specifically for each method call.
*
* @created by Introduce Toolkit version 1.0
*/
public class RegistrationConsumerClient extends ServiceSecurityClient implements RegistrationConsumer {
protected RegistrationConsumerPortType portType;
private Object portTypeMutex;
public RegistrationConsumerClient(String url) throws MalformedURIException, RemoteException {
this(url,null);
}
public RegistrationConsumerClient(String url, GlobusCredential proxy) throws MalformedURIException, RemoteException {
super(url,proxy);
initialize();
}
public RegistrationConsumerClient(EndpointReferenceType epr) throws MalformedURIException, RemoteException {
this(epr,null);
}
public RegistrationConsumerClient(EndpointReferenceType epr, GlobusCredential proxy) throws MalformedURIException, RemoteException {
super(epr,proxy);
initialize();
}
private void initialize() throws RemoteException {
this.portTypeMutex = new Object();
this.portType = createPortType();
}
private RegistrationConsumerPortType createPortType() throws RemoteException {
RegistrationConsumerServiceAddressingLocator locator = new RegistrationConsumerServiceAddressingLocator();
// attempt to load our context sensitive wsdd file
InputStream resourceAsStream = ClassUtils.getResourceAsStream(getClass(), "client-config.wsdd");
if (resourceAsStream != null) {
// we found it, so tell axis to configure an engine to use it
EngineConfiguration engineConfig = new FileProvider(resourceAsStream);
// set the engine of the locator
locator.setEngine(new AxisClient(engineConfig));
}
RegistrationConsumerPortType port = null;
try {
port = locator.getRegistrationConsumerPortTypePort(getEndpointReference());
} catch (Exception e) {
throw new RemoteException("Unable to locate portType:" + e.getMessage(), e);
}
return port;
}
public GetResourcePropertyResponse getResourceProperty(QName resourcePropertyQName) throws RemoteException {
return portType.getResourceProperty(resourcePropertyQName);
}
public static void usage(){
System.out.println(RegistrationConsumerClient.class.getName() + " -url <service url>");
}
public static void main(String [] args) {
System.out.println("Running the Grid Service Client");
try{
if(!(args.length < 4)){
if(args[0].equals("-url")){
RegistrationConsumerClient client = new RegistrationConsumerClient(args[1]);
if(args[2].equals("-message")){
gov.nih.nci.cabig.ctms.grid.RegistrationType registrationMessage = (gov.nih.nci.cabig.ctms.grid.RegistrationType) Utils.deserializeDocument(args[3],gov.nih.nci.cabig.ctms.grid.RegistrationType.class);
System.out.println("Registering with gridID " + registrationMessage.getStudyGridId());
client.register(registrationMessage);
}
}
else {
usage();
System.exit(1);
}
} else {
usage();
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public void register(gov.nih.nci.cabig.ctms.grid.RegistrationType registration) throws RemoteException, gov.nih.nci.cabig.ctms.stubs.types.InvalidRegistration, gov.nih.nci.cabig.ctms.stubs.types.RegistrationFailed {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"register");
gov.nih.nci.cabig.ctms.stubs.RegisterRequest params = new gov.nih.nci.cabig.ctms.stubs.RegisterRequest();
gov.nih.nci.cabig.ctms.stubs.RegisterRequestRegistration registrationContainer = new gov.nih.nci.cabig.ctms.stubs.RegisterRequestRegistration();
registrationContainer.setRegistration(registration);
params.setRegistration(registrationContainer);
gov.nih.nci.cabig.ctms.stubs.RegisterResponse boxedResult = portType.register(params);
}
}
public gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata getServiceSecurityMetadata() throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"getServiceSecurityMetadata");
gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataRequest params = new gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataRequest();
gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataResponse boxedResult = portType.getServiceSecurityMetadata(params);
return boxedResult.getServiceSecurityMetadata();
}
}
}
| codebase/projects/grid/RegistrationConsumer/src/gov/nih/nci/cabig/ctms/client/RegistrationConsumerClient.java | package gov.nih.nci.cabig.ctms.client;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.StringReader;
import java.rmi.RemoteException;
import javax.xml.namespace.QName;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.client.AxisClient;
import org.apache.axis.client.Stub;
import org.apache.axis.configuration.FileProvider;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.axis.types.URI.MalformedURIException;
import org.apache.axis.utils.ClassUtils;
import org.oasis.wsrf.properties.GetResourcePropertyResponse;
import org.globus.gsi.GlobusCredential;
import gov.nih.nci.cabig.ctms.stubs.RegistrationConsumerPortType;
import gov.nih.nci.cabig.ctms.stubs.service.RegistrationConsumerServiceAddressingLocator;
import gov.nih.nci.cabig.ctms.common.RegistrationConsumer;
import gov.nih.nci.cabig.esb.*;
import gov.nih.nci.cagrid.introduce.security.client.ServiceSecurityClient;
import gov.nih.nci.cagrid.common.Utils;
/**
* This class is autogenerated, DO NOT EDIT GENERATED GRID SERVICE METHODS.
*
* This client is generated automatically by Introduce to provide a clean unwrapped API to the
* service.
*
* On construction the class instance will contact the remote service and retrieve it's security
* metadata description which it will use to configure the Stub specifically for each method call.
*
* @created by Introduce Toolkit version 1.0
*/
public class RegistrationConsumerClient extends ServiceSecurityClient implements RegistrationConsumer {
protected RegistrationConsumerPortType portType;
private Object portTypeMutex;
public RegistrationConsumerClient(String url) throws MalformedURIException, RemoteException {
this(url,null);
}
public RegistrationConsumerClient(String url, GlobusCredential proxy) throws MalformedURIException, RemoteException {
super(url,proxy);
initialize();
}
public RegistrationConsumerClient(EndpointReferenceType epr) throws MalformedURIException, RemoteException {
this(epr,null);
}
public RegistrationConsumerClient(EndpointReferenceType epr, GlobusCredential proxy) throws MalformedURIException, RemoteException {
super(epr,proxy);
initialize();
}
private void initialize() throws RemoteException {
this.portTypeMutex = new Object();
this.portType = createPortType();
}
private RegistrationConsumerPortType createPortType() throws RemoteException {
RegistrationConsumerServiceAddressingLocator locator = new RegistrationConsumerServiceAddressingLocator();
// attempt to load our context sensitive wsdd file
InputStream resourceAsStream = ClassUtils.getResourceAsStream(getClass(), "client-config.wsdd");
if (resourceAsStream != null) {
// we found it, so tell axis to configure an engine to use it
EngineConfiguration engineConfig = new FileProvider(resourceAsStream);
// set the engine of the locator
locator.setEngine(new AxisClient(engineConfig));
}
RegistrationConsumerPortType port = null;
try {
port = locator.getRegistrationConsumerPortTypePort(getEndpointReference());
} catch (Exception e) {
throw new RemoteException("Unable to locate portType:" + e.getMessage(), e);
}
return port;
}
public GetResourcePropertyResponse getResourceProperty(QName resourcePropertyQName) throws RemoteException {
return portType.getResourceProperty(resourcePropertyQName);
}
public static void usage(){
System.out.println(RegistrationConsumerClient.class.getName() + " -url <service url>");
}
public static void main(String [] args) {
System.out.println("Running the Grid Service Client");
try{
if(!(args.length < 4)){
if(args[0].equals("-url")){
RegistrationConsumerClient client = new RegistrationConsumerClient(args[1]);
if(args[2].equals("-message")){
ESBMessageDocument doc = ESBMessageDocument.Factory.parse(new File(args[3]));
StringReader messageReader = new StringReader(doc.getESBMessage().getMessage().toString());
gov.nih.nci.cabig.ctms.grid.RegistrationType registrationMessage = (gov.nih.nci.cabig.ctms.grid.RegistrationType) Utils.deserializeObject(messageReader,gov.nih.nci.cabig.ctms.grid.RegistrationType.class);
System.out.println("Registering with gridID " + registrationMessage.getStudyGridId());
client.register(registrationMessage);
}
}
else {
usage();
System.exit(1);
}
} else {
usage();
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public void register(gov.nih.nci.cabig.ctms.grid.RegistrationType registration) throws RemoteException, gov.nih.nci.cabig.ctms.stubs.types.InvalidRegistration, gov.nih.nci.cabig.ctms.stubs.types.RegistrationFailed {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"register");
gov.nih.nci.cabig.ctms.stubs.RegisterRequest params = new gov.nih.nci.cabig.ctms.stubs.RegisterRequest();
gov.nih.nci.cabig.ctms.stubs.RegisterRequestRegistration registrationContainer = new gov.nih.nci.cabig.ctms.stubs.RegisterRequestRegistration();
registrationContainer.setRegistration(registration);
params.setRegistration(registrationContainer);
gov.nih.nci.cabig.ctms.stubs.RegisterResponse boxedResult = portType.register(params);
}
}
public gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata getServiceSecurityMetadata() throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"getServiceSecurityMetadata");
gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataRequest params = new gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataRequest();
gov.nih.nci.cagrid.introduce.security.stubs.GetServiceSecurityMetadataResponse boxedResult = portType.getServiceSecurityMetadata(params);
return boxedResult.getServiceSecurityMetadata();
}
}
}
| rollback
| codebase/projects/grid/RegistrationConsumer/src/gov/nih/nci/cabig/ctms/client/RegistrationConsumerClient.java | rollback | <ide><path>odebase/projects/grid/RegistrationConsumer/src/gov/nih/nci/cabig/ctms/client/RegistrationConsumerClient.java
<ide> package gov.nih.nci.cabig.ctms.client;
<ide>
<ide> import java.io.InputStream;
<del>import java.io.FileInputStream;
<del>import java.io.File;
<del>import java.io.StringReader;
<ide> import java.rmi.RemoteException;
<ide>
<ide> import javax.xml.namespace.QName;
<ide> import gov.nih.nci.cabig.ctms.stubs.RegistrationConsumerPortType;
<ide> import gov.nih.nci.cabig.ctms.stubs.service.RegistrationConsumerServiceAddressingLocator;
<ide> import gov.nih.nci.cabig.ctms.common.RegistrationConsumer;
<del>import gov.nih.nci.cabig.esb.*;
<ide> import gov.nih.nci.cagrid.introduce.security.client.ServiceSecurityClient;
<ide> import gov.nih.nci.cagrid.common.Utils;
<ide>
<ide> if(args[0].equals("-url")){
<ide> RegistrationConsumerClient client = new RegistrationConsumerClient(args[1]);
<ide> if(args[2].equals("-message")){
<del> ESBMessageDocument doc = ESBMessageDocument.Factory.parse(new File(args[3]));
<ide>
<del> StringReader messageReader = new StringReader(doc.getESBMessage().getMessage().toString());
<del>
<del> gov.nih.nci.cabig.ctms.grid.RegistrationType registrationMessage = (gov.nih.nci.cabig.ctms.grid.RegistrationType) Utils.deserializeObject(messageReader,gov.nih.nci.cabig.ctms.grid.RegistrationType.class);
<add> gov.nih.nci.cabig.ctms.grid.RegistrationType registrationMessage = (gov.nih.nci.cabig.ctms.grid.RegistrationType) Utils.deserializeDocument(args[3],gov.nih.nci.cabig.ctms.grid.RegistrationType.class);
<ide> System.out.println("Registering with gridID " + registrationMessage.getStudyGridId());
<ide> client.register(registrationMessage);
<ide> } |
|
Java | bsd-3-clause | 93fd0f9e3d7c6a0cdf6e23ccb1b75975610c5eed | 0 | FRC4564/AerialsAssist | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/* This version modified by team 4564 for 2014 robot "Natasha" competition. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
//import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Joystick;
//import edu.wpi.first.wpilibj.Relay;
//import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
public class Natasha2014 extends SimpleRobot {
// Global constants
public static final int PWM_DRIVE_FL = 4;
public static final int PWM_DRIVE_RL = 3;
public static final int PWM_DRIVE_FR = 2;
public static final int PWM_DRIVE_RR = 1;
public static final int JB_DRIVE_SLOW = 2;
public static final double TIMER_DELAY_SECS = .01;
// Global variables
// Define robot components
Talon leftForward = new Talon(PWM_DRIVE_FL);
Talon leftBackward = new Talon(PWM_DRIVE_RL);
Talon rightForward = new Talon(PWM_DRIVE_FR);
Talon rightBackward = new Talon(PWM_DRIVE_RR);
RobotDrive chassis = new RobotDrive(leftForward,leftBackward,rightForward,rightBackward);
Joystick leftstick = new Joystick(1);
Joystick rightstick = new Joystick(2);
/**
* Robot initialization runs once at startup
*/
protected void robotInit() {
chassis.setInvertedMotor(RobotDrive.MotorType.kFrontLeft,true);
chassis.setInvertedMotor(RobotDrive.MotorType.kRearLeft,true);
chassis.setInvertedMotor(RobotDrive.MotorType.kFrontRight,true);
chassis.setInvertedMotor(RobotDrive.MotorType.kRearRight,true);
}
/**
* Autonomous mode is called once and must exit before 10 sec period expires
*/
public void autonomous() {
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
chassis.setSafetyEnabled(true);
while(isOperatorControl() && isEnabled()){
if (leftstick.getRawButton(JB_DRIVE_SLOW)) {
chassis.arcadeDrive(leftstick.getY() * .7, leftstick.getX() * .5);
} else {
chassis.arcadeDrive(leftstick.getY(), leftstick.getX() * .7);
}
Timer.delay(TIMER_DELAY_SECS);
}
}
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
}
| src/edu/wpi/first/wpilibj/templates/Natasha2014.java | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/* This version modified by team 4564 for 2014 robot "Natasha" competition. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
//import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
public class Natasha2014 extends SimpleRobot {
// Global constants
public static final int PWM_DRIVE_FL = 4;
public static final int PWM_DRIVE_RL = 3;
public static final int PWM_DRIVE_FR = 2;
public static final int PWM_DRIVE_RR = 1;
public static final int JB_DRIVE_SLOW = 2;
public static final double TIMER_DELAY_SECS = .01;
// Global variables
// Define robot components
Talon leftForward = new Talon(PWM_DRIVE_FL);
Talon leftBackward = new Talon(PWM_DRIVE_RL);
Talon rightForward = new Talon(PWM_DRIVE_FR);
Talon rightBackward = new Talon(PWM_DRIVE_RR);
RobotDrive chassis = new RobotDrive(leftForward,leftBackward,rightForward,rightBackward);
Joystick leftstick = new Joystick(1);
Joystick rightstick = new Joystick(2);
/**
* Robot initialization runs once at startup
*/
protected void robotInit() {
chassis.setInvertedMotor(RobotDrive.MotorType.kFrontLeft,true);
chassis.setInvertedMotor(RobotDrive.MotorType.kRearLeft,true);
chassis.setInvertedMotor(RobotDrive.MotorType.kFrontRight,true);
chassis.setInvertedMotor(RobotDrive.MotorType.kRearRight,true);
}
/**
* Autonomous mode is called once and must exit before 10 sec period expires
*/
public void autonomous() {
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
chassis.setSafetyEnabled(true);
while(isOperatorControl() && isEnabled()){
if (leftstick.getRawButton(JB_DRIVE_SLOW)) {
chassis.arcadeDrive(leftstick.getY() * .7, leftstick.getX() * .5);
} else {
chassis.arcadeDrive(leftstick.getY(), leftstick.getX() * .7);
}
Timer.delay(TIMER_DELAY_SECS);
}
}
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
}
| Commented out unused imports | src/edu/wpi/first/wpilibj/templates/Natasha2014.java | Commented out unused imports | <ide><path>rc/edu/wpi/first/wpilibj/templates/Natasha2014.java
<ide> import edu.wpi.first.wpilibj.SimpleRobot;
<ide> import edu.wpi.first.wpilibj.RobotDrive;
<ide> import edu.wpi.first.wpilibj.Joystick;
<del>import edu.wpi.first.wpilibj.Relay;
<del>import edu.wpi.first.wpilibj.Solenoid;
<add>//import edu.wpi.first.wpilibj.Relay;
<add>//import edu.wpi.first.wpilibj.Solenoid;
<ide> import edu.wpi.first.wpilibj.Talon;
<ide> import edu.wpi.first.wpilibj.Timer;
<ide> |
|
Java | apache-2.0 | b89612f7dadf0eb77ff43541fd0301530f690e2d | 0 | berkantkz/KLU_Yemek,berkantkz/KLU_Yemek,berkantkz/KLU_Yemek | package io.github.berkantkz.klu;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import io.github.berkantkz.klu.Utils.TinyDB;
public class MainActivity extends Activity {
TinyDB tinydb;
static ArrayList<KLU_List> list;
static KLU_Adapter adapter;
private InterstitialAd mInterstitialAd;
@SuppressLint("StaticFieldLeak")
static ProgressBar pb;
int counter = 0;
static String today, date, day, content = "";
@SuppressLint("StaticFieldLeak")
static TextView tv_today, today_top;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tinydb = new TinyDB(getApplicationContext());
MobileAds.initialize(getApplicationContext(),"ca-app-pub-2951689275458403~2892686723");
startInterstitialAd();
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
pb = findViewById(R.id.pb);
list = new ArrayList<>();
final GridView gridView = findViewById(R.id.gv);
tv_today = findViewById(R.id.tv_today);
today_top = findViewById(R.id.today_top);
gridView.setPadding(0,0,0, AdSize.BANNER.getHeightInPixels(this));
adapter = new KLU_Adapter(getApplicationContext(), R.layout.row, list);
gridView.setAdapter(adapter);
startInterstitialAd();
new JSONAsyncTask().execute("https://berkantkz.github.io/KLU_Yemek/list.json");
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new AlertDialog.Builder(MainActivity.this, R.style.DialogTheme)
.setTitle(list.get(position).getDate().replace("-01-"," Ocak ").replace("-02-", " Şubat ").replace("-03-"," Mart ").replace("-04-", " Nisan ").replace("-05-", " Mayıs ").replace("-06-"," Haziran ").replace("-07-", " Temmuz ").replace("-08-", " Ağustos ").replace("-09-", " Eylül ").replace("-10-" ," Ekim ").replace("-11-", " Kasım ").replace("-12-", " Aralık ").toUpperCase() + list.get(position).getDay())
.setMessage(list.get(position).getContent().replace(",",""))
.setPositiveButton("KAPAT", null)
.setCancelable(false)
.show();
startInterstitialAd();
}
});
}
private static class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jarray = new JSONArray(data);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
KLU_List KLUList = new KLU_List();
KLUList.setDay(object.getString("day"));
KLUList.setContent(object.getString("content"));
KLUList.setDate(object.getString("date"));
list.add(KLUList);
Time rn = new Time(Time.getCurrentTimezone());
rn.setToNow();
int month = rn.month + 1;
int monthday = rn.monthDay;
int year = rn.year;
today = year + "-" + month + "-" + monthday;
date = object.getString("date").replace("-0","-").replace(" ", "");
if (date.equals(today)) {
content = object.getString("content");
day = object.getString("day");
date = date.replace("-01-"," Ocak ").replace("-02-", " Şubat ").replace("-03-"," Mart ").replace("-04-", " Nisan ").replace("-05-", " Mayıs ").replace("-06-"," Haziran ").replace("-07-", " Temmuz ").replace("-08-", " Ağustos ").replace("-09-", " Eylül ").replace("-10-" ," Ekim ").replace("-11-", " Kasım ").replace("-12-", " Aralık ").toUpperCase() + " " + day;
}
}
return true;
}
} catch ( IOException | JSONException e) {
e.printStackTrace();
}
return false;
}
@SuppressLint("SetTextI18n")
protected void onPostExecute(Boolean result) {
adapter.notifyDataSetChanged();
pb.setVisibility(View.GONE);
if (!content.equals("")) {
today_top.setText("BUGÜN: " + today);
tv_today.setText(content);
} else {
tv_today.setText("Bugün için herhangi bir veri kullanılabilir değil.");
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_about) {
new AlertDialog.Builder(MainActivity.this, R.style.DialogTheme)
.setTitle("Hakkında")
.setMessage("Kullanılan liste Kırklareli Üniversitesi resmi web sayfasından alınmıştır. \n\nUygulama kaynağı GitHub'da bulunabilir. \n\n - Berkant Korkmaz, berkantkz")
.setPositiveButton("KAPAT", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
counter++;
if (counter == 4) {
tinydb.putBoolean("isAdsDisabled",true);
Toast.makeText(MainActivity.this, "Reklâmlar devre dışı bırakıldı.", Toast.LENGTH_SHORT).show();
}
}
})
.setNeutralButton("Kaynağa git", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("https://github.com/berkantkz/KLU_Yemek");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
})
.show();
startInterstitialAd();
}
return super.onOptionsItemSelected(item);
}
public void startInterstitialAd() {
if (!tinydb.getBoolean("isAdsDisabled")) {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-2951689275458403/2628252404");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
mInterstitialAd.show();
}
});
} else {
Log.d("KLU_YEMEK"," berkantkz presents!!");
}
}
}
| app/src/main/java/io/github/berkantkz/klu/MainActivity.java | package io.github.berkantkz.klu;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import io.github.berkantkz.klu.Utils.TinyDB;
public class MainActivity extends Activity {
TinyDB tinydb;
static ArrayList<KLU_List> list;
static KLU_Adapter adapter;
private InterstitialAd mInterstitialAd;
@SuppressLint("StaticFieldLeak")
static ProgressBar pb;
int counter = 0;
static String today, date, day, content = "";
@SuppressLint("StaticFieldLeak")
static TextView tv_today, today_top;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tinydb = new TinyDB(getApplicationContext());
MobileAds.initialize(getApplicationContext(),"ca-app-pub-2951689275458403~2892686723");
startInterstitialAd();
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
pb = findViewById(R.id.pb);
list = new ArrayList<>();
final GridView gridView = findViewById(R.id.gv);
tv_today = findViewById(R.id.tv_today);
today_top = findViewById(R.id.today_top);
gridView.setPadding(0,0,0, AdSize.BANNER.getHeightInPixels(this));
adapter = new KLU_Adapter(getApplicationContext(), R.layout.row, list);
gridView.setAdapter(adapter);
startInterstitialAd();
new JSONAsyncTask().execute("https://berkantkz.github.io/KLU_Yemek/list.json");
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new AlertDialog.Builder(MainActivity.this, R.style.DialogTheme)
.setTitle(list.get(position).getDate().replace("-01-"," Ocak ").replace("-02-", " Şubat ").replace("-03-"," Mart ").replace("-04-", " Nisan ").replace("-05-", " Mayıs ").replace("-06-"," Haziran ").replace("-07-", " Temmuz ").replace("-08-", " Ağustos ").replace("-09-", " Eylül ").replace("-10-" ," Ekim ").replace("-11-", " Kasım ").replace("-12-", " Aralık ").toUpperCase() + list.get(position).getDay())
.setMessage(list.get(position).getContent().replace(",",""))
.setPositiveButton("KAPAT", null)
.show();
startInterstitialAd();
}
});
}
private static class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jarray = new JSONArray(data);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
KLU_List KLUList = new KLU_List();
KLUList.setDay(object.getString("day"));
KLUList.setContent(object.getString("content"));
KLUList.setDate(object.getString("date"));
list.add(KLUList);
Time rn = new Time(Time.getCurrentTimezone());
rn.setToNow();
int month = rn.month + 1;
int monthday = rn.monthDay;
int year = rn.year;
today = year + "-" + month + "-" + monthday;
date = object.getString("date").replace("-0","-").replace(" ", "");
if (date.equals(today)) {
content = object.getString("content");
day = object.getString("day");
date = date.replace("-01-"," Ocak ").replace("-02-", " Şubat ").replace("-03-"," Mart ").replace("-04-", " Nisan ").replace("-05-", " Mayıs ").replace("-06-"," Haziran ").replace("-07-", " Temmuz ").replace("-08-", " Ağustos ").replace("-09-", " Eylül ").replace("-10-" ," Ekim ").replace("-11-", " Kasım ").replace("-12-", " Aralık ").toUpperCase() + " " + day;
}
}
return true;
}
} catch ( IOException | JSONException e) {
e.printStackTrace();
}
return false;
}
@SuppressLint("SetTextI18n")
protected void onPostExecute(Boolean result) {
adapter.notifyDataSetChanged();
pb.setVisibility(View.GONE);
if (!content.equals("")) {
today_top.setText("BUGÜN: " + today);
tv_today.setText(content);
} else {
tv_today.setText("Bugün için herhangi bir veri kullanılabilir değil.");
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_about) {
new AlertDialog.Builder(MainActivity.this, R.style.DialogTheme)
.setTitle("Hakkında")
.setMessage("Kullanılan liste Kırklareli Üniversitesi resmi web sayfasından alınmıştır. \n\nUygulama kaynağı GitHub'da bulunabilir. \n\n - Berkant Korkmaz, berkantkz")
.setPositiveButton("KAPAT", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
counter++;
if (counter == 4) {
tinydb.putBoolean("isAdsDisabled",true);
Toast.makeText(MainActivity.this, "Reklâmlar devre dışı bırakıldı.", Toast.LENGTH_SHORT).show();
}
}
})
.setNeutralButton("Kaynağa git", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("https://github.com/berkantkz/KLU_Yemek");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
})
.show();
startInterstitialAd();
}
return super.onOptionsItemSelected(item);
}
public void startInterstitialAd() {
if (!tinydb.getBoolean("isAdsDisabled")) {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-2951689275458403/2628252404");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
mInterstitialAd.show();
}
});
} else {
Log.d("KLU_YEMEK"," berkantkz presents!!");
}
}
}
| MainActivity: Don't dismiss the dialog screen on touch
when touched to the outside of the dialog
| app/src/main/java/io/github/berkantkz/klu/MainActivity.java | MainActivity: Don't dismiss the dialog screen on touch | <ide><path>pp/src/main/java/io/github/berkantkz/klu/MainActivity.java
<ide> .setTitle(list.get(position).getDate().replace("-01-"," Ocak ").replace("-02-", " Şubat ").replace("-03-"," Mart ").replace("-04-", " Nisan ").replace("-05-", " Mayıs ").replace("-06-"," Haziran ").replace("-07-", " Temmuz ").replace("-08-", " Ağustos ").replace("-09-", " Eylül ").replace("-10-" ," Ekim ").replace("-11-", " Kasım ").replace("-12-", " Aralık ").toUpperCase() + list.get(position).getDay())
<ide> .setMessage(list.get(position).getContent().replace(",",""))
<ide> .setPositiveButton("KAPAT", null)
<add> .setCancelable(false)
<ide> .show();
<ide> startInterstitialAd();
<ide> } |
|
Java | apache-2.0 | 9105ce14655ab93daee20de387951d7209f89385 | 0 | AsuraTeam/dubbos,AsuraTeam/dubbos,AsuraTeam/dubbos | /*
* Copyright 1999-2011 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.remoting.transport.dispather;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.store.DataStore;
import com.alibaba.dubbo.common.threadpool.ThreadPool;
import com.alibaba.dubbo.common.utils.NamedThreadFactory;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.ChannelHandler;
import com.alibaba.dubbo.remoting.RemotingException;
import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate;
public class WrappedChannelHandler implements ChannelHandlerDelegate {
protected static final Logger logger = LoggerFactory.getLogger(WrappedChannelHandler.class);
protected static final ExecutorService SHARED_EXECUTOR = Executors.newCachedThreadPool(new NamedThreadFactory("DubboSharedHandler", true));
protected final ExecutorService executor;
protected final ChannelHandler handler;
protected final URL url;
public WrappedChannelHandler(ChannelHandler handler, URL url) {
this.handler = handler;
this.url = url;
executor = (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url);
String componentKey = Constants.EXECUTOR_SERVICE_COMPONENT_KEY;
if (Constants.CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(Constants.SIDE_KEY))) {
componentKey = Constants.CONSUMER_SIDE;
}
DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
dataStore.put(componentKey, Integer.toString(url.getPort()), executor);
}
public void close() {
try {
if (executor instanceof ExecutorService) {
((ExecutorService)executor).shutdown();
}
} catch (Throwable t) {
logger.warn("fail to destroy thread pool of server: " + t.getMessage(), t);
}
}
public void connected(Channel channel) throws RemotingException {
handler.connected(channel);
}
public void disconnected(Channel channel) throws RemotingException {
handler.disconnected(channel);
}
public void sent(Channel channel, Object message) throws RemotingException {
handler.sent(channel, message);
}
@SuppressWarnings("deprecation")
public void received(Channel channel, Object message) throws RemotingException {
handler.received(channel, message);
}
public void caught(Channel channel, Throwable exception) throws RemotingException {
handler.caught(channel, exception);
}
public ExecutorService getExecutor() {
return executor;
}
public ChannelHandler getHandler() {
if (handler instanceof ChannelHandlerDelegate) {
return ((ChannelHandlerDelegate) handler).getHandler();
} else {
return handler;
}
}
public URL getUrl() {
return url;
}
} | dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/WrappedChannelHandler.java | /*
* Copyright 1999-2011 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.remoting.transport.dispather;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.store.DataStore;
import com.alibaba.dubbo.common.threadpool.ThreadPool;
import com.alibaba.dubbo.common.utils.NamedThreadFactory;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.ChannelHandler;
import com.alibaba.dubbo.remoting.RemotingException;
import com.alibaba.dubbo.remoting.transport.ChannelHandlerDelegate;
public class WrappedChannelHandler implements ChannelHandlerDelegate {
protected static final Logger logger = LoggerFactory.getLogger(WrappedChannelHandler.class);
protected static final ExecutorService SHARED_EXECUTOR = Executors.newCachedThreadPool(new NamedThreadFactory("DubboSharedHandler", true));
protected final ExecutorService executor;
protected final ChannelHandler handler;
protected final URL url;
public WrappedChannelHandler(ChannelHandler handler, URL url) {
this.handler = handler;
this.url = url;
executor = (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url);
if (Constants.PROVIDER_SIDE.equalsIgnoreCase(url.getParameter(Constants.SIDE_KEY))) {
DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
dataStore.put(Constants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort()), executor);
}
if (Constants.CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(Constants.SIDE_KEY))) {
DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
dataStore.put(Constants.CONSUMER_SIDE, Integer.toString(url.getPort()), executor);
}
}
public void close() {
try {
if (executor instanceof ExecutorService) {
((ExecutorService)executor).shutdown();
}
} catch (Throwable t) {
logger.warn("fail to destroy thread pool of server: " + t.getMessage(), t);
}
}
public void connected(Channel channel) throws RemotingException {
handler.connected(channel);
}
public void disconnected(Channel channel) throws RemotingException {
handler.disconnected(channel);
}
public void sent(Channel channel, Object message) throws RemotingException {
handler.sent(channel, message);
}
@SuppressWarnings("deprecation")
public void received(Channel channel, Object message) throws RemotingException {
handler.received(channel, message);
}
public void caught(Channel channel, Throwable exception) throws RemotingException {
handler.caught(channel, exception);
}
public ExecutorService getExecutor() {
return executor;
}
public ChannelHandler getHandler() {
if (handler instanceof ChannelHandlerDelegate) {
return ((ChannelHandlerDelegate) handler).getHandler();
} else {
return handler;
}
}
public URL getUrl() {
return url;
}
} | DUBBO-122 Provider的线程池监控支持
| dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/WrappedChannelHandler.java | DUBBO-122 Provider的线程池监控支持 | <ide><path>ubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/WrappedChannelHandler.java
<ide> this.url = url;
<ide> executor = (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url);
<ide>
<del> if (Constants.PROVIDER_SIDE.equalsIgnoreCase(url.getParameter(Constants.SIDE_KEY))) {
<del> DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
<del> dataStore.put(Constants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort()), executor);
<add> String componentKey = Constants.EXECUTOR_SERVICE_COMPONENT_KEY;
<add> if (Constants.CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(Constants.SIDE_KEY))) {
<add> componentKey = Constants.CONSUMER_SIDE;
<ide> }
<del> if (Constants.CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(Constants.SIDE_KEY))) {
<del> DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
<del> dataStore.put(Constants.CONSUMER_SIDE, Integer.toString(url.getPort()), executor);
<del> }
<add> DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
<add> dataStore.put(componentKey, Integer.toString(url.getPort()), executor);
<ide> }
<ide>
<ide> public void close() { |
|
Java | lgpl-2.1 | dd0798d4917fa396a7d982613a18ec547f98d6df | 0 | mediaworx/opencms-core,serrapos/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,alkacon/opencms-core,victos/opencms-core,victos/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,MenZil/opencms-core,serrapos/opencms-core,victos/opencms-core,victos/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,gallardo/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,serrapos/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/workplace/explorer/CmsResourceUtil.java,v $
* Date : $Date: 2008/04/02 07:14:57 $
* Version: $Revision: 1.14 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.workplace.explorer;
import org.opencms.db.CmsDbEntryNotFoundException;
import org.opencms.db.CmsResourceState;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypePlain;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.i18n.CmsMessages;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.security.CmsOrganizationalUnit;
import org.opencms.security.CmsPermissionSet;
import org.opencms.security.CmsPermissionSetCustom;
import org.opencms.security.CmsPrincipal;
import org.opencms.util.A_CmsModeIntEnumeration;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.commons.CmsTouch;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
/**
* Provides {@link CmsResource} utility functions.<p>
*
* This class provides in java all resource information used by the explorer view,
* mostly generated in javascript (see explorer.js)<p>
*
* @author Michael Moossen
*
* @version $Revision: 1.14 $
*
* @since 6.0.0
*/
public final class CmsResourceUtil {
/**
* Enumeration class for defining the resource project state.<p>
*/
public static class CmsResourceProjectState extends A_CmsModeIntEnumeration {
/** Constant for the project state unlocked. */
protected static final CmsResourceProjectState CLEAN = new CmsResourceProjectState(0);
/** Constant for the project state locked for publishing. */
protected static final CmsResourceProjectState LOCKED_FOR_PUBLISHING = new CmsResourceProjectState(5);
/** Constant for the project state locked in current project. */
protected static final CmsResourceProjectState MODIFIED_IN_CURRENT_PROJECT = new CmsResourceProjectState(1);
/** Constant for the project state locked in other project. */
protected static final CmsResourceProjectState MODIFIED_IN_OTHER_PROJECT = new CmsResourceProjectState(2);
private static final long serialVersionUID = 4580450220255428716L;
/**
* Default constructor.<p>
*
* @param mode the mode descriptor
*/
protected CmsResourceProjectState(int mode) {
super(mode);
}
/**
* Checks if this is a {@link #LOCKED_FOR_PUBLISHING} state.<p>
*
* @return <code>true</code> if this is a {@link #LOCKED_FOR_PUBLISHING} state
*/
public boolean isLockedForPublishing() {
return (this == LOCKED_FOR_PUBLISHING);
}
/**
* Checks if this is a {@link #MODIFIED_IN_CURRENT_PROJECT} state.<p>
*
* @return <code>true</code> if this is a {@link #MODIFIED_IN_CURRENT_PROJECT} state
*/
public boolean isModifiedInCurrentProject() {
return (this == MODIFIED_IN_CURRENT_PROJECT);
}
/**
* Checks if this is a {@link #MODIFIED_IN_OTHER_PROJECT} state.<p>
*
* @return <code>true</code> if this is a {@link #MODIFIED_IN_OTHER_PROJECT} state
*/
public boolean isModifiedInOtherProject() {
return (this == MODIFIED_IN_OTHER_PROJECT);
}
/**
* Checks if this is a {@link #CLEAN} state.<p>
*
* @return <code>true</code> if this is a {@link #CLEAN} state
*/
public boolean isUnlocked() {
return (this == CLEAN);
}
}
/**
* Enumeration class for defining the site modes.<p>
*/
private static class CmsResourceUtilSiteMode {
/**
* Default constructor.<p>
*/
protected CmsResourceUtilSiteMode() {
// noop
}
}
/** Layout style for resources after expire date. */
public static final int LAYOUTSTYLE_AFTEREXPIRE = 2;
/** Layout style for resources before release date. */
public static final int LAYOUTSTYLE_BEFORERELEASE = 1;
/** Layout style for resources after release date and before expire date. */
public static final int LAYOUTSTYLE_INRANGE = 0;
/** Constant that signalizes that all path operations will be based on the current site. */
public static final CmsResourceUtilSiteMode SITE_MODE_CURRENT = new CmsResourceUtilSiteMode();
/** Constant that signalizes that all path operations will be based on the best matching site. */
public static final CmsResourceUtilSiteMode SITE_MODE_MATCHING = new CmsResourceUtilSiteMode();
/** Constant that signalizes that all path operations will be based on the root path. */
public static final CmsResourceUtilSiteMode SITE_MODE_ROOT = new CmsResourceUtilSiteMode();
/** Constant for the project state locked for publishing. */
public static final CmsResourceProjectState STATE_LOCKED_FOR_PUBLISHING = CmsResourceProjectState.LOCKED_FOR_PUBLISHING;
/** Constant for the project state locked in current project. */
public static final CmsResourceProjectState STATE_MODIFIED_IN_CURRENT_PROJECT = CmsResourceProjectState.MODIFIED_IN_CURRENT_PROJECT;
/** Constant for the project state locked in other project. */
public static final CmsResourceProjectState STATE_MODIFIED_IN_OTHER_PROJECT = CmsResourceProjectState.MODIFIED_IN_OTHER_PROJECT;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsResourceUtil.class);
/** The folder size display string constant. */
private static final String SIZE_DIR = "-";
/** Constant for the project state unlocked. */
private static final CmsResourceProjectState STATE_CLEAN = CmsResourceProjectState.CLEAN;
/** If greater than zero, the path will be formatted to this number of chars. */
private int m_abbrevLength;
/** The current cms context. */
private CmsObject m_cms;
/** The current resource lock. */
private CmsLock m_lock;
/** The message bundle for formatting dates, depends on the request locale. */
private CmsMessages m_messages;
/** Reference project resources cache. */
private List m_projectResources;
/** The project to use to check project state, if <code>null</code> the current project will be used. */
private CmsProject m_referenceProject;
/** The 'relative to' path. */
private String m_relativeTo;
/** The current request context. */
private CmsRequestContext m_request;
/** The current resource. */
private CmsResource m_resource;
/** The current resource type. */
private I_CmsResourceType m_resourceType;
/** The current site mode. */
private CmsResourceUtilSiteMode m_siteMode = SITE_MODE_CURRENT;
/**
* Creates a new {@link CmsResourceUtil} object.<p>
*
* @param cms the cms context
*/
public CmsResourceUtil(CmsObject cms) {
setCms(cms);
}
/**
* Creates a new {@link CmsResourceUtil} object.<p>
*
* @param cms the cms context
* @param resource the resource
*/
public CmsResourceUtil(CmsObject cms, CmsResource resource) {
setCms(cms);
setResource(resource);
}
/**
* Creates a new {@link CmsResourceUtil} object.<p>
*
* @param resource the resource
*/
public CmsResourceUtil(CmsResource resource) {
setResource(resource);
}
/**
* Returns the path abbreviation length.<p>
*
* If greater than zero, the path will be formatted to this number of chars.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @return the path abbreviation Length
*/
public int getAbbrevLength() {
return m_abbrevLength;
}
/**
* Returns the cms context.<p>
*
* @return the cms context
*/
public CmsObject getCms() {
return m_cms;
}
/**
* Returns the formatted date of expiration.<p>
*
* @return the formatted date of expiration
*/
public String getDateExpired() {
long release = m_resource.getDateExpired();
if (release != CmsResource.DATE_EXPIRED_DEFAULT) {
return getMessages().getDateTime(release);
} else {
return CmsTouch.DEFAULT_DATE_STRING;
}
}
/**
* Returns the formatted date of release.<p>
*
* @return the formatted date of release
*/
public String getDateReleased() {
long release = m_resource.getDateReleased();
if (release != CmsResource.DATE_RELEASED_DEFAULT) {
return getMessages().getDateTime(release);
} else {
return CmsTouch.DEFAULT_DATE_STRING;
}
}
/**
* Returns the path of the current resource, taking into account just the site mode.<p>
*
* @return the full path
*/
public String getFullPath() {
String path = m_resource.getRootPath();
if ((m_siteMode != SITE_MODE_ROOT) && (m_cms != null)) {
String site = getSite();
if (path.startsWith(site)) {
path = path.substring(site.length());
}
}
return path;
}
/**
* Returns the resource icon path displayed in the explorer view for the given resource.<p>
*
* Relative to <code>/system/workplace/resources/</code>.<p>
*
* If the resource has no sibling it is the same as {@link #getIconPathResourceType()}.<p>
*
* @return the resource icon path displayed in the explorer view for the given resource
*
* @see #getStyleSiblings()
*/
public String getIconPathExplorer() {
if (m_resource.getSiblingCount() > 1) {
// links are present
if (m_resource.isLabeled()) {
// there is at least one link in a marked site
return "explorer/link_labeled.gif";
} else {
// common links are present
return "explorer/link.gif";
}
} else {
return getIconPathResourceType();
}
}
/**
* Returns the lock icon path for the given resource.<p>
*
* Relative to <code>/system/workplace/resources/</code>.<p>
*
* Returns <code>explorer/project_none.gif</code> if request context is <code>null</code>.<p>
*
* @return the lock icon path for the given resource
*/
public String getIconPathLock() {
CmsLock lock = getLock();
String iconPath = null;
if (!lock.isUnlocked() && (m_request != null) && isInsideProject()) {
if (getLock().isOwnedBy(m_request.currentUser())
&& (getLockedInProjectId().equals(getReferenceProject().getUuid()))) {
if (lock.isShared()) {
iconPath = "shared";
} else {
iconPath = "user";
}
} else {
iconPath = "other";
}
}
if (iconPath == null) {
iconPath = "project_none";
} else {
iconPath = "lock_" + iconPath;
}
return "explorer/" + iconPath + ".gif";
}
/**
* Returns the project state icon path for the given resource.<p>
*
* Relative to <code>/system/workplace/resources/</code>.<p>
*
* @return the project state icon path for the given resource
*/
public String getIconPathProjectState() {
String iconPath;
if (getProjectState() == STATE_MODIFIED_IN_CURRENT_PROJECT) {
iconPath = "this.png";
} else if (getProjectState() == STATE_MODIFIED_IN_OTHER_PROJECT) {
iconPath = "other.png";
} else if (getProjectState() == STATE_LOCKED_FOR_PUBLISHING) {
iconPath = "publish.png";
} else {
// STATE_UNLOCKED
iconPath = "none.gif";
}
return "explorer/project_" + iconPath;
}
/**
* Returns the resource type icon path for the given resource.<p>
*
* Relative to <code>/system/workplace/resources/</code>.<p>
*
* @return the resource type icon path for the given resource
*/
public String getIconPathResourceType() {
if (!isEditable()) {
return "filetypes/"
+ OpenCms.getWorkplaceManager().getExplorerTypeSetting(CmsResourceTypePlain.getStaticTypeName()).getIcon();
}
return "filetypes/" + OpenCms.getWorkplaceManager().getExplorerTypeSetting(getResourceTypeName()).getIcon();
}
/**
* Returns an integer representation for the link type.<p>
*
* <ul>
* <li><code>0</code>: No sibling
* <li><code>1</code>: Sibling
* <li><code>2</code>: Labeled sibling
* </ul>
*
* @return an integer representation for the link type
*/
public int getLinkType() {
if (m_resource.getSiblingCount() > 1) {
// links are present
if (m_resource.isLabeled()) {
// there is at least one link in a marked site
return 2;
} else {
// common links are present
return 1;
}
} else {
// no links to the resource are in the VFS
return 0;
}
}
/**
* Returns the the lock for the given resource.<p>
*
* @return the lock the given resource
*/
public CmsLock getLock() {
if (m_lock == null) {
try {
m_lock = getCms().getLock(m_resource);
} catch (Throwable e) {
m_lock = CmsLock.getNullLock();
LOG.error(e.getLocalizedMessage(), e);
}
}
return m_lock;
}
/**
* Returns the user name who owns the lock for the given resource.<p>
*
* @return the user name who owns the lock for the given resource
*/
public String getLockedByName() {
String lockedBy = "";
if (!getLock().isNullLock()) {
// user
lockedBy = getLock().getUserId().toString();
try {
lockedBy = getCurrentOuRelativeName(CmsPrincipal.readPrincipalIncludingHistory(
getCms(),
getLock().getUserId()).getName());
} catch (Throwable e) {
lockedBy = e.getMessage();
}
}
return lockedBy;
}
/**
* Returns the id of the project in which the given resource is locked.<p>
*
* @return the id of the project in which the given resource is locked
*/
public CmsUUID getLockedInProjectId() {
CmsUUID lockedInProject = null;
if (getLock().isNullLock() && !getResource().getState().isUnchanged()) {
// resource is unlocked and modified
lockedInProject = getResource().getProjectLastModified();
} else if (!getResource().getState().isUnchanged()) {
// resource is locked and modified
lockedInProject = getProjectId();
} else if (!getLock().isNullLock()) {
// resource is locked and unchanged
lockedInProject = getLock().getProjectId();
}
return lockedInProject;
}
/**
* Returns the project name that locked the current resource's.<p>
*
* @return the the project name that locked the current resource's
*/
public String getLockedInProjectName() {
try {
CmsUUID pId = getLockedInProjectId();
if ((pId == null) || pId.isNullUUID()) {
// the resource is unlocked and unchanged
return "";
}
try {
return getCurrentOuRelativeName(getCms().readProject(pId).getName());
} catch (CmsDbEntryNotFoundException e) {
return getCurrentOuRelativeName(getCms().readHistoryProject(pId).getName());
}
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
return "";
}
}
/**
* Returns the lock state of the current resource.<p>
*
* @return the lock state of the current resource
*/
public int getLockState() {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(getLockedByName())) {
// unlocked
return 0;
}
if (!getLockedByName().equals(getCurrentOuRelativeName(m_request.currentUser().getName()))
|| !getLockedInProjectId().equals(m_request.currentProject().getUuid())) {
// locked by other user and/or project
return 1;
}
if (getLock().getType().isShared()) {
// shared lock
return 2;
}
// exclusive lock
return 3;
}
/**
* Returns the navtext of a resource.<p>
*
* @return the navtext for that resource
*/
public String getNavText() {
String navText = "";
try {
navText = getCms().readPropertyObject(
getCms().getSitePath(m_resource),
CmsPropertyDefinition.PROPERTY_NAVTEXT,
false).getValue();
} catch (Throwable e) {
String storedSiteRoot = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot("");
navText = getCms().readPropertyObject(
m_resource.getRootPath(),
CmsPropertyDefinition.PROPERTY_NAVTEXT,
false).getValue();
} catch (Exception e1) {
// should usually never happen
if (LOG.isInfoEnabled()) {
LOG.info(e);
}
} finally {
getCms().getRequestContext().setSiteRoot(storedSiteRoot);
}
}
if (navText == null) {
navText = "";
}
return navText;
}
/**
* Returns the path of the current resource.<p>
*
* Taking into account following settings:<br>
* <ul>
* <li>site mode
* <li>abbreviation length
* <li>relative to
* </ul>
*
* @return the path
*/
public String getPath() {
String path = getFullPath();
if (m_relativeTo != null) {
path = getResource().getRootPath();
if (path.startsWith(m_relativeTo)) {
path = path.substring(m_relativeTo.length());
if (path.length() == 0) {
path = ".";
}
} else {
String site = getSite();
if (path.startsWith(site + "/") || path.equals(site)) {
path = path.substring(site.length());
}
}
}
if (m_abbrevLength > 0) {
boolean absolute = path.startsWith("/");
path = CmsStringUtil.formatResourceName(path, m_abbrevLength);
if (!absolute && path.startsWith("/")) {
// remove leading '/'
path = path.substring(1);
}
}
return path;
}
/**
* Returns the permission set for the given resource.<p>
*
* @return the permission set for the given resource
*/
public CmsPermissionSet getPermissionSet() {
CmsPermissionSetCustom pset = new CmsPermissionSetCustom();
CmsResource resource = getResource();
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_CONTROL, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_CONTROL);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_CONTROL);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_DIRECT_PUBLISH, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_DIRECT_PUBLISH);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_DIRECT_PUBLISH);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_READ, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_READ);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_READ);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_VIEW, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_VIEW);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_VIEW);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_WRITE);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_WRITE);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
return pset;
}
/**
* Returns the permissions string for the given resource.<p>
*
* @return the permissions string for the given resource
*/
public String getPermissionString() {
return getPermissionSet().getPermissionString();
}
/**
* Returns the id of the project which the resource belongs to.<p>
*
* @return the id of the project which the resource belongs to
*/
public CmsUUID getProjectId() {
CmsUUID projectId = m_resource.getProjectLastModified();
if (!getLock().isUnlocked() && !getLock().isInherited()) {
// use lock project ID only if lock is not inherited
projectId = getLock().getProjectId();
}
return projectId;
}
/**
* Returns the project state of the given resource.<p>
*
* <ul>
* <li>null: unchanged.</li>
* <li>true: locked in current project.</li>
* <li>false: not locked in current project.</li>
* </ul>
*
* @return the project state of the given resource
*/
public CmsResourceProjectState getProjectState() {
if (getResource().getState().isUnchanged()) {
return STATE_CLEAN; // STATE_CLEAN
} else if (getLock().getSystemLock().isPublish()) {
return STATE_LOCKED_FOR_PUBLISHING;
} else if (getResource().getProjectLastModified().equals(getReferenceProject().getUuid())) {
return STATE_MODIFIED_IN_CURRENT_PROJECT; // STATE_MODIFIED_CURRENT_PROJECT
} else {
return STATE_MODIFIED_IN_OTHER_PROJECT; // STATE_MODIFIED_OTHER_PROJECT
}
}
/**
* Returns the project to use to check project state.<p>
*
* @return the project to use to check project state
*/
public CmsProject getReferenceProject() {
if (m_referenceProject == null) {
if (m_request != null) {
m_referenceProject = m_request.currentProject();
}
}
return m_referenceProject;
}
/**
* Returns the 'relative to' path.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @return the 'relative to' path
*/
public String getRelativeTo() {
return m_relativeTo;
}
/**
* Returns the resource.<p>
*
* @return the resource
*/
public CmsResource getResource() {
return m_resource;
}
/**
* Returns the resource type for the given resource.<p>
*
* @return the resource type for the given resource
*/
public I_CmsResourceType getResourceType() {
if (m_resourceType == null) {
m_resourceType = OpenCms.getResourceManager().getResourceType(m_resource);
}
return m_resourceType;
}
/**
* Returns the resource type id for the given resource.<p>
*
* @return the resource type id for the given resource
*/
public int getResourceTypeId() {
return getResourceType().getTypeId();
}
/**
* Returns the resource type name for the given resource.<p>
*
* @return the resource type name for the given resource
*/
public String getResourceTypeName() {
return getResourceType().getTypeName();
}
/**
* Returns the site of the current resources,
* taking into account the set site mode.<p>
*
* @return the site path
*/
public String getSite() {
String site = null;
if ((m_siteMode == SITE_MODE_MATCHING) || (m_cms == null)) {
site = OpenCms.getSiteManager().getSiteRoot(m_resource.getRootPath());
} else if (m_siteMode == SITE_MODE_CURRENT) {
site = m_cms.getRequestContext().getSiteRoot();
} else if (m_siteMode == SITE_MODE_ROOT) {
site = "";
}
return (site == null ? "" : site);
}
/**
* Returns the site mode.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @return the site mode
*/
public CmsResourceUtilSiteMode getSiteMode() {
return m_siteMode;
}
/**
* Returns the title of the site.<p>
*
* @return the title of the site
*/
public String getSiteTitle() {
String title = getSite();
String rootSite = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot("");
title = getCms().readPropertyObject(title, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue(title);
} catch (CmsException e) {
// ignore
} finally {
getCms().getRequestContext().setSiteRoot(rootSite);
}
return title;
}
/**
* Returns the size of the given resource as a String.<p>
*
* For directories it returns <code>SIZE_DIR</code>.<p>
*
* @return the size of the given resource as a String
*/
public String getSizeString() {
return m_resource.getLength() == -1 ? SIZE_DIR : "" + m_resource.getLength();
}
/**
* Returns resource state abbreviation.<p>
*
* @return resource state abbreviation
*/
public char getStateAbbreviation() {
return getResource().getState().getAbbreviation();
}
/**
* Returns the state name for a resource.<p>
*
* Uses default locale if request context is <code>null</code>.<p>
*
* @return the state name for that resource
*/
public String getStateName() {
CmsResourceState state = m_resource.getState();
String name;
if (m_request == null) {
name = org.opencms.workplace.explorer.Messages.get().getBundle().key(
org.opencms.workplace.explorer.Messages.getStateKey(state));
} else {
name = org.opencms.workplace.explorer.Messages.get().getBundle(m_request.getLocale()).key(
org.opencms.workplace.explorer.Messages.getStateKey(state));
}
return name;
}
/**
* Returns the style class to use for the given resource.<p>
*
* @return style class name
*
* @see org.opencms.workplace.list.CmsListExplorerColumn#getExplorerStyleDef()
*/
public String getStyleClassName() {
if (isInsideProject() && isEditable()) {
if (m_resource.getState().isChanged()) {
return "fc";
} else if (m_resource.getState().isNew()) {
return "fn";
} else if (m_resource.getState().isDeleted()) {
return "fd";
} else {
return "nf";
}
}
return "fp";
}
/**
* Returns additional style sheets for the resource type icon depending on siblings.<p>
*
* That is, depending on {@link CmsResource#getSiblingCount()}
*
* Use it with the {@link #getIconPathExplorer} method.<p>
*
* @return additional style sheets depending on siblings
*/
public String getStyleSiblings() {
StringBuffer style = new StringBuffer(128);
if (m_resource.getSiblingCount() > 1) {
style.append("background-image:url(");
style.append(CmsWorkplace.getSkinUri());
style.append(getIconPathResourceType());
style.append("); background-position: 0px 0px; background-repeat: no-repeat; ");
}
return style.toString();
}
/**
* Returns the system lock information tooltip for the explorer view.<p>
*
* @param forExplorer if the tool tip should be generated for the explorer view
*
* @return the system lock information tooltip
*/
public String getSystemLockInfo(boolean forExplorer) {
if (getLock().getSystemLock().isPublish()) {
if (!forExplorer) {
return getMessages().key(Messages.GUI_PUBLISH_TOOLTIP_0);
} else {
// see explorer.js(sysLockInfo) and top_js.jsp(publishlock)
return "p"; // should have length == 1
}
}
return "";
}
/**
* Returns additional style sheets depending on publication constraints.<p>
*
* That is, depending on {@link CmsResource#getDateReleased()} and
* {@link CmsResource#getDateExpired()}.<p>
*
* @return additional style sheets depending on publication constraints
*
* @see #getTimeWindowLayoutType()
*/
public String getTimeWindowLayoutStyle() {
return getTimeWindowLayoutType() == CmsResourceUtil.LAYOUTSTYLE_INRANGE ? "" : "font-style:italic;";
}
/**
* Returns the layout style for the current time window state.<p>
*
* <ul>
* <li><code>{@link CmsResourceUtil#LAYOUTSTYLE_INRANGE}</code>: The time window is in range
* <li><code>{@link CmsResourceUtil#LAYOUTSTYLE_BEFORERELEASE}</code>: The resource is not yet released
* <li><code>{@link CmsResourceUtil#LAYOUTSTYLE_AFTEREXPIRE}</code>: The resource has already expired
* </ul>
*
* @return the layout style for the current time window state
*
* @see #getTimeWindowLayoutStyle()
*/
public int getTimeWindowLayoutType() {
int layoutstyle = CmsResourceUtil.LAYOUTSTYLE_INRANGE;
if (!m_resource.isReleased(getCms().getRequestContext().getRequestTime())) {
layoutstyle = CmsResourceUtil.LAYOUTSTYLE_BEFORERELEASE;
} else if (m_resource.isExpired(getCms().getRequestContext().getRequestTime())) {
layoutstyle = CmsResourceUtil.LAYOUTSTYLE_AFTEREXPIRE;
}
return layoutstyle;
}
/**
* Returns the title of a resource.<p>
*
* @return the title for that resource
*/
public String getTitle() {
String title = "";
try {
title = getCms().readPropertyObject(
getCms().getSitePath(m_resource),
CmsPropertyDefinition.PROPERTY_TITLE,
false).getValue();
} catch (Throwable e) {
String storedSiteRoot = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot("");
title = getCms().readPropertyObject(
m_resource.getRootPath(),
CmsPropertyDefinition.PROPERTY_TITLE,
false).getValue();
} catch (Exception e1) {
// should usually never happen
if (LOG.isInfoEnabled()) {
LOG.info(e);
}
} finally {
getCms().getRequestContext().setSiteRoot(storedSiteRoot);
}
}
if (title == null) {
title = "";
}
return title;
}
/**
* Returns the name of the user who created the given resource.<p>
*
* @return the name of the user who created the given resource
*/
public String getUserCreated() {
String user = m_resource.getUserCreated().toString();
try {
user = getCurrentOuRelativeName(CmsPrincipal.readPrincipalIncludingHistory(
getCms(),
m_resource.getUserCreated()).getName());
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage());
}
return user;
}
/**
* Returns the name of the user who last modified the given resource.<p>
*
* @return the name of the user who last modified the given resource
*/
public String getUserLastModified() {
String user = m_resource.getUserLastModified().toString();
try {
user = getCurrentOuRelativeName(CmsPrincipal.readPrincipalIncludingHistory(
getCms(),
m_resource.getUserLastModified()).getName());
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage());
}
return user;
}
/**
* Returns <code>true</code> if the given resource is editable by the current user.<p>
*
* Returns <code>false</code> if no request context is set.<p>
*
* @return <code>true</code> if the given resource is editable by the current user
*/
public boolean isEditable() {
if (m_request == null) {
return false;
}
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(getResourceTypeName());
if (settings != null) {
String rightSite = OpenCms.getSiteManager().getSiteRoot(getResource().getRootPath());
if (rightSite == null) {
rightSite = "";
}
String currentSite = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot(rightSite);
return settings.isEditable(getCms(), getResource());
} finally {
getCms().getRequestContext().setSiteRoot(currentSite);
}
}
return false;
}
/**
* Returns <code>true</code> if the given resource is in the reference project.<p>
*
* Returns <code>false</code> if the request context is <code>null</code>.<p>
*
* @return <code>true</code> if the given resource is in the reference project
*
* @see #getReferenceProject()
*/
public boolean isInsideProject() {
return CmsProject.isInsideProject(getProjectResources(), getResource());
}
/**
* Returns <code>true</code> if the stored resource has been released and has not expired.<p>
*
* If no request context is available, the current time is used for the validation check.<p>
*
* @return <code>true</code> if the stored resource has been released and has not expired
*
* @see CmsResource#isReleasedAndNotExpired(long)
*/
public boolean isReleasedAndNotExpired() {
long requestTime;
if (m_request == null) {
requestTime = System.currentTimeMillis();
} else {
requestTime = m_request.getRequestTime();
}
return m_resource.isReleasedAndNotExpired(requestTime);
}
/**
* Sets the path abbreviation length.<p>
*
* If greater than zero, the path will be formatted to this number of chars.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @param abbrevLength the path abbreviation length to set
*/
public void setAbbrevLength(int abbrevLength) {
m_abbrevLength = abbrevLength;
}
/**
* Sets the cms context.<p>
*
* @param cms the cms context to set
*/
public void setCms(CmsObject cms) {
m_cms = cms;
m_request = cms.getRequestContext();
m_referenceProject = null;
m_projectResources = null;
m_messages = null;
}
/**
* Sets the project to use to check project state.<p>
*
* @param project the project to set
*/
public void setReferenceProject(CmsProject project) {
m_referenceProject = project;
m_projectResources = null;
}
/**
* Sets the 'relative to' path.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @param relativeTo the 'relative to' path to set
*/
public void setRelativeTo(String relativeTo) {
m_relativeTo = relativeTo;
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_relativeTo)) {
m_relativeTo = null;
} else {
if (!m_relativeTo.startsWith("/")) {
m_relativeTo = "/" + m_relativeTo;
}
if (!m_relativeTo.endsWith("/")) {
m_relativeTo += "/";
}
}
}
/**
* Sets the resource.<p>
*
* @param resource the resource to set
*/
public void setResource(CmsResource resource) {
m_resource = resource;
m_lock = null;
m_resourceType = null;
}
/**
* Sets the site mode.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @param siteMode the site mode to set
*/
public void setSiteMode(CmsResourceUtilSiteMode siteMode) {
m_siteMode = siteMode;
}
/**
* Returns the simple name if the ou is the same as the current user's ou.<p>
*
* @param name the fully qualified name to check
*
* @return the simple name if the ou is the same as the current user's ou
*/
private String getCurrentOuRelativeName(String name) {
if (m_request == null) {
return CmsOrganizationalUnit.SEPARATOR + name;
}
String ou = CmsOrganizationalUnit.getParentFqn(name);
if (ou.equals(m_request.currentUser().getOuFqn())) {
return CmsOrganizationalUnit.getSimpleName(name);
}
return CmsOrganizationalUnit.SEPARATOR + name;
}
/**
* Returns the message bundle for formatting dates, depends on the request locale.<p>
*
* @return the message bundle for formatting dates
*/
private CmsMessages getMessages() {
if (m_messages == null) {
if (m_request != null) {
m_messages = Messages.get().getBundle(m_request.getLocale());
} else {
m_messages = Messages.get().getBundle();
}
}
return m_messages;
}
/**
* Returns the reference project resources.<p>
*
* @return the reference project resources
*/
private List getProjectResources() {
if (m_projectResources == null) {
try {
m_projectResources = getCms().readProjectResources(getReferenceProject());
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
// use an empty list (all resources are "outside")
m_projectResources = new ArrayList();
}
}
return m_projectResources;
}
} | src/org/opencms/workplace/explorer/CmsResourceUtil.java | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/workplace/explorer/CmsResourceUtil.java,v $
* Date : $Date: 2008/03/27 16:50:41 $
* Version: $Revision: 1.13 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.workplace.explorer;
import org.opencms.db.CmsDbEntryNotFoundException;
import org.opencms.db.CmsResourceState;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypePlain;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.i18n.CmsMessages;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.security.CmsOrganizationalUnit;
import org.opencms.security.CmsPermissionSet;
import org.opencms.security.CmsPermissionSetCustom;
import org.opencms.security.CmsPrincipal;
import org.opencms.util.A_CmsModeIntEnumeration;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.commons.CmsTouch;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
/**
* Provides {@link CmsResource} utility functions.<p>
*
* This class provides in java all resource information used by the explorer view,
* mostly generated in javascript (see explorer.js)<p>
*
* @author Michael Moossen
*
* @version $Revision: 1.13 $
*
* @since 6.0.0
*/
public final class CmsResourceUtil {
/**
* Enumeration class for defining the resource project state.<p>
*/
public static class CmsResourceProjectState extends A_CmsModeIntEnumeration {
/** Constant for the project state unlocked. */
protected static final CmsResourceProjectState CLEAN = new CmsResourceProjectState(0);
/** Constant for the project state locked for publishing. */
protected static final CmsResourceProjectState LOCKED_FOR_PUBLISHING = new CmsResourceProjectState(5);
/** Constant for the project state locked in current project. */
protected static final CmsResourceProjectState MODIFIED_IN_CURRENT_PROJECT = new CmsResourceProjectState(1);
/** Constant for the project state locked in other project. */
protected static final CmsResourceProjectState MODIFIED_IN_OTHER_PROJECT = new CmsResourceProjectState(2);
private static final long serialVersionUID = 4580450220255428716L;
/**
* Default constructor.<p>
*
* @param mode the mode descriptor
*/
protected CmsResourceProjectState(int mode) {
super(mode);
}
/**
* Checks if this is a {@link #LOCKED_FOR_PUBLISHING} state.<p>
*
* @return <code>true</code> if this is a {@link #LOCKED_FOR_PUBLISHING} state
*/
public boolean isLockedForPublishing() {
return (this == LOCKED_FOR_PUBLISHING);
}
/**
* Checks if this is a {@link #MODIFIED_IN_CURRENT_PROJECT} state.<p>
*
* @return <code>true</code> if this is a {@link #MODIFIED_IN_CURRENT_PROJECT} state
*/
public boolean isModifiedInCurrentProject() {
return (this == MODIFIED_IN_CURRENT_PROJECT);
}
/**
* Checks if this is a {@link #MODIFIED_IN_OTHER_PROJECT} state.<p>
*
* @return <code>true</code> if this is a {@link #MODIFIED_IN_OTHER_PROJECT} state
*/
public boolean isModifiedInOtherProject() {
return (this == MODIFIED_IN_OTHER_PROJECT);
}
/**
* Checks if this is a {@link #CLEAN} state.<p>
*
* @return <code>true</code> if this is a {@link #CLEAN} state
*/
public boolean isUnlocked() {
return (this == CLEAN);
}
}
/**
* Enumeration class for defining the site modes.<p>
*/
private static class CmsResourceUtilSiteMode {
/**
* Default constructor.<p>
*/
protected CmsResourceUtilSiteMode() {
// noop
}
}
/** Layout style for resources after expire date. */
public static final int LAYOUTSTYLE_AFTEREXPIRE = 2;
/** Layout style for resources before release date. */
public static final int LAYOUTSTYLE_BEFORERELEASE = 1;
/** Layout style for resources after release date and before expire date. */
public static final int LAYOUTSTYLE_INRANGE = 0;
/** Constant that signalizes that all path operations will be based on the current site. */
public static final CmsResourceUtilSiteMode SITE_MODE_CURRENT = new CmsResourceUtilSiteMode();
/** Constant that signalizes that all path operations will be based on the best matching site. */
public static final CmsResourceUtilSiteMode SITE_MODE_MATCHING = new CmsResourceUtilSiteMode();
/** Constant that signalizes that all path operations will be based on the root path. */
public static final CmsResourceUtilSiteMode SITE_MODE_ROOT = new CmsResourceUtilSiteMode();
/** Constant for the project state locked for publishing. */
public static final CmsResourceProjectState STATE_LOCKED_FOR_PUBLISHING = CmsResourceProjectState.LOCKED_FOR_PUBLISHING;
/** Constant for the project state locked in current project. */
public static final CmsResourceProjectState STATE_MODIFIED_IN_CURRENT_PROJECT = CmsResourceProjectState.MODIFIED_IN_CURRENT_PROJECT;
/** Constant for the project state locked in other project. */
public static final CmsResourceProjectState STATE_MODIFIED_IN_OTHER_PROJECT = CmsResourceProjectState.MODIFIED_IN_OTHER_PROJECT;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsResourceUtil.class);
/** The folder size display string constant. */
private static final String SIZE_DIR = "-";
/** Constant for the project state unlocked. */
private static final CmsResourceProjectState STATE_CLEAN = CmsResourceProjectState.CLEAN;
/** If greater than zero, the path will be formatted to this number of chars. */
private int m_abbrevLength;
/** The current cms context. */
private CmsObject m_cms;
/** The current resource lock. */
private CmsLock m_lock;
/** The message bundle for formatting dates, depends on the request locale. */
private CmsMessages m_messages;
/** Reference project resources cache. */
private List m_projectResources;
/** The project to use to check project state, if <code>null</code> the current project will be used. */
private CmsProject m_referenceProject;
/** The 'relative to' path. */
private String m_relativeTo;
/** The current request context. */
private CmsRequestContext m_request;
/** The current resource. */
private CmsResource m_resource;
/** The current resource type. */
private I_CmsResourceType m_resourceType;
/** The current site mode. */
private CmsResourceUtilSiteMode m_siteMode = SITE_MODE_CURRENT;
/**
* Creates a new {@link CmsResourceUtil} object.<p>
*
* @param cms the cms context
*/
public CmsResourceUtil(CmsObject cms) {
setCms(cms);
}
/**
* Creates a new {@link CmsResourceUtil} object.<p>
*
* @param cms the cms context
* @param resource the resource
*/
public CmsResourceUtil(CmsObject cms, CmsResource resource) {
setCms(cms);
setResource(resource);
}
/**
* Creates a new {@link CmsResourceUtil} object.<p>
*
* @param resource the resource
*/
public CmsResourceUtil(CmsResource resource) {
setResource(resource);
}
/**
* Returns the path abbreviation length.<p>
*
* If greater than zero, the path will be formatted to this number of chars.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @return the path abbreviation Length
*/
public int getAbbrevLength() {
return m_abbrevLength;
}
/**
* Returns the cms context.<p>
*
* @return the cms context
*/
public CmsObject getCms() {
return m_cms;
}
/**
* Returns the formatted date of expiration.<p>
*
* @return the formatted date of expiration
*/
public String getDateExpired() {
long release = m_resource.getDateExpired();
if (release != CmsResource.DATE_EXPIRED_DEFAULT) {
return getMessages().getDateTime(release);
} else {
return CmsTouch.DEFAULT_DATE_STRING;
}
}
/**
* Returns the formatted date of release.<p>
*
* @return the formatted date of release
*/
public String getDateReleased() {
long release = m_resource.getDateReleased();
if (release != CmsResource.DATE_RELEASED_DEFAULT) {
return getMessages().getDateTime(release);
} else {
return CmsTouch.DEFAULT_DATE_STRING;
}
}
/**
* Returns the path of the current resource, taking into account just the site mode.<p>
*
* @return the full path
*/
public String getFullPath() {
String path = m_resource.getRootPath();
if ((m_siteMode != SITE_MODE_ROOT) && (m_cms != null)) {
String site = getSite();
if (path.startsWith(site)) {
path = path.substring(site.length());
}
}
return path;
}
/**
* Returns the resource icon path displayed in the explorer view for the given resource.<p>
*
* Relative to <code>/system/workplace/resources/</code>.<p>
*
* If the resource has no sibling it is the same as {@link #getIconPathResourceType()}.<p>
*
* @return the resource icon path displayed in the explorer view for the given resource
*
* @see #getStyleSiblings()
*/
public String getIconPathExplorer() {
if (m_resource.getSiblingCount() > 1) {
// links are present
if (m_resource.isLabeled()) {
// there is at least one link in a marked site
return "explorer/link_labeled.gif";
} else {
// common links are present
return "explorer/link.gif";
}
} else {
return getIconPathResourceType();
}
}
/**
* Returns the lock icon path for the given resource.<p>
*
* Relative to <code>/system/workplace/resources/</code>.<p>
*
* Returns <code>explorer/project_none.gif</code> if request context is <code>null</code>.<p>
*
* @return the lock icon path for the given resource
*/
public String getIconPathLock() {
CmsLock lock = getLock();
String iconPath = null;
if (!lock.isUnlocked() && (m_request != null) && isInsideProject()) {
if (getLock().isOwnedBy(m_request.currentUser())
&& (getLockedInProjectId().equals(getReferenceProject().getUuid()))) {
if (lock.isShared()) {
iconPath = "shared";
} else {
iconPath = "user";
}
} else {
iconPath = "other";
}
}
if (iconPath == null) {
iconPath = "project_none";
} else {
iconPath = "lock_" + iconPath;
}
return "explorer/" + iconPath + ".gif";
}
/**
* Returns the project state icon path for the given resource.<p>
*
* Relative to <code>/system/workplace/resources/</code>.<p>
*
* @return the project state icon path for the given resource
*/
public String getIconPathProjectState() {
String iconPath;
if (getProjectState() == STATE_MODIFIED_IN_CURRENT_PROJECT) {
iconPath = "this.png";
} else if (getProjectState() == STATE_MODIFIED_IN_OTHER_PROJECT) {
iconPath = "other.png";
} else if (getProjectState() == STATE_LOCKED_FOR_PUBLISHING) {
iconPath = "publish.png";
} else {
// STATE_UNLOCKED
iconPath = "none.gif";
}
return "explorer/project_" + iconPath;
}
/**
* Returns the resource type icon path for the given resource.<p>
*
* Relative to <code>/system/workplace/resources/</code>.<p>
*
* @return the resource type icon path for the given resource
*/
public String getIconPathResourceType() {
if (!isEditable()) {
return "filetypes/"
+ OpenCms.getWorkplaceManager().getExplorerTypeSetting(CmsResourceTypePlain.getStaticTypeName()).getIcon();
}
return "filetypes/" + OpenCms.getWorkplaceManager().getExplorerTypeSetting(getResourceTypeName()).getIcon();
}
/**
* Returns an integer representation for the link type.<p>
*
* <ul>
* <li><code>0</code>: No sibling
* <li><code>1</code>: Sibling
* <li><code>2</code>: Labeled sibling
* </ul>
*
* @return an integer representation for the link type
*/
public int getLinkType() {
if (m_resource.getSiblingCount() > 1) {
// links are present
if (m_resource.isLabeled()) {
// there is at least one link in a marked site
return 2;
} else {
// common links are present
return 1;
}
} else {
// no links to the resource are in the VFS
return 0;
}
}
/**
* Returns the the lock for the given resource.<p>
*
* @return the lock the given resource
*/
public CmsLock getLock() {
if (m_lock == null) {
try {
m_lock = getCms().getLock(m_resource);
} catch (Throwable e) {
m_lock = CmsLock.getNullLock();
LOG.error(e.getLocalizedMessage(), e);
}
}
return m_lock;
}
/**
* Returns the user name who owns the lock for the given resource.<p>
*
* @return the user name who owns the lock for the given resource
*/
public String getLockedByName() {
String lockedBy = "";
if (!getLock().isNullLock()) {
try {
lockedBy = getCurrentOuRelativeName(getCms().readUser(getLock().getUserId()).getName());
} catch (Throwable e) {
lockedBy = e.getMessage();
}
}
return lockedBy;
}
/**
* Returns the id of the project in which the given resource is locked.<p>
*
* @return the id of the project in which the given resource is locked
*/
public CmsUUID getLockedInProjectId() {
CmsUUID lockedInProject = null;
if (getLock().isNullLock() && !getResource().getState().isUnchanged()) {
// resource is unlocked and modified
lockedInProject = getResource().getProjectLastModified();
} else if (!getResource().getState().isUnchanged()) {
// resource is locked and modified
lockedInProject = getProjectId();
} else if (!getLock().isNullLock()) {
// resource is locked and unchanged
lockedInProject = getLock().getProjectId();
}
return lockedInProject;
}
/**
* Returns the project name that locked the current resource's.<p>
*
* @return the the project name that locked the current resource's
*/
public String getLockedInProjectName() {
try {
CmsUUID pId = getLockedInProjectId();
if ((pId == null) || pId.isNullUUID()) {
// the resource is unlocked and unchanged
return "";
}
try {
return getCurrentOuRelativeName(getCms().readProject(pId).getName());
} catch (CmsDbEntryNotFoundException e) {
return getCurrentOuRelativeName(getCms().readHistoryProject(pId).getName());
}
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
return "";
}
}
/**
* Returns the lock state of the current resource.<p>
*
* @return the lock state of the current resource
*/
public int getLockState() {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(getLockedByName())) {
// unlocked
return 0;
}
if (!getLockedByName().equals(getCurrentOuRelativeName(m_request.currentUser().getName()))
|| !getLockedInProjectId().equals(m_request.currentProject().getUuid())) {
// locked by other user and/or project
return 1;
}
if (getLock().getType().isShared()) {
// shared lock
return 2;
}
// exclusive lock
return 3;
}
/**
* Returns the navtext of a resource.<p>
*
* @return the navtext for that resource
*/
public String getNavText() {
String navText = "";
try {
navText = getCms().readPropertyObject(
getCms().getSitePath(m_resource),
CmsPropertyDefinition.PROPERTY_NAVTEXT,
false).getValue();
} catch (Throwable e) {
String storedSiteRoot = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot("");
navText = getCms().readPropertyObject(
m_resource.getRootPath(),
CmsPropertyDefinition.PROPERTY_NAVTEXT,
false).getValue();
} catch (Exception e1) {
// should usually never happen
if (LOG.isInfoEnabled()) {
LOG.info(e);
}
} finally {
getCms().getRequestContext().setSiteRoot(storedSiteRoot);
}
}
if (navText == null) {
navText = "";
}
return navText;
}
/**
* Returns the path of the current resource.<p>
*
* Taking into account following settings:<br>
* <ul>
* <li>site mode
* <li>abbreviation length
* <li>relative to
* </ul>
*
* @return the path
*/
public String getPath() {
String path = getFullPath();
if (m_relativeTo != null) {
path = getResource().getRootPath();
if (path.startsWith(m_relativeTo)) {
path = path.substring(m_relativeTo.length());
if (path.length() == 0) {
path = ".";
}
} else {
String site = getSite();
if (path.startsWith(site + "/") || path.equals(site)) {
path = path.substring(site.length());
}
}
}
if (m_abbrevLength > 0) {
boolean absolute = path.startsWith("/");
path = CmsStringUtil.formatResourceName(path, m_abbrevLength);
if (!absolute && path.startsWith("/")) {
// remove leading '/'
path = path.substring(1);
}
}
return path;
}
/**
* Returns the permission set for the given resource.<p>
*
* @return the permission set for the given resource
*/
public CmsPermissionSet getPermissionSet() {
CmsPermissionSetCustom pset = new CmsPermissionSetCustom();
CmsResource resource = getResource();
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_CONTROL, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_CONTROL);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_CONTROL);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_DIRECT_PUBLISH, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_DIRECT_PUBLISH);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_DIRECT_PUBLISH);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_READ, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_READ);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_READ);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_VIEW, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_VIEW);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_VIEW);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
try {
if (getCms().hasPermissions(resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL)) {
pset.grantPermissions(CmsPermissionSet.PERMISSION_WRITE);
} else {
pset.denyPermissions(CmsPermissionSet.PERMISSION_WRITE);
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage());
}
return pset;
}
/**
* Returns the permissions string for the given resource.<p>
*
* @return the permissions string for the given resource
*/
public String getPermissionString() {
return getPermissionSet().getPermissionString();
}
/**
* Returns the id of the project which the resource belongs to.<p>
*
* @return the id of the project which the resource belongs to
*/
public CmsUUID getProjectId() {
CmsUUID projectId = m_resource.getProjectLastModified();
if (!getLock().isUnlocked() && !getLock().isInherited()) {
// use lock project ID only if lock is not inherited
projectId = getLock().getProjectId();
}
return projectId;
}
/**
* Returns the project state of the given resource.<p>
*
* <ul>
* <li>null: unchanged.</li>
* <li>true: locked in current project.</li>
* <li>false: not locked in current project.</li>
* </ul>
*
* @return the project state of the given resource
*/
public CmsResourceProjectState getProjectState() {
if (getResource().getState().isUnchanged()) {
return STATE_CLEAN; // STATE_CLEAN
} else if (getLock().getSystemLock().isPublish()) {
return STATE_LOCKED_FOR_PUBLISHING;
} else if (getResource().getProjectLastModified().equals(getReferenceProject().getUuid())) {
return STATE_MODIFIED_IN_CURRENT_PROJECT; // STATE_MODIFIED_CURRENT_PROJECT
} else {
return STATE_MODIFIED_IN_OTHER_PROJECT; // STATE_MODIFIED_OTHER_PROJECT
}
}
/**
* Returns the project to use to check project state.<p>
*
* @return the project to use to check project state
*/
public CmsProject getReferenceProject() {
if (m_referenceProject == null) {
if (m_request != null) {
m_referenceProject = m_request.currentProject();
}
}
return m_referenceProject;
}
/**
* Returns the 'relative to' path.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @return the 'relative to' path
*/
public String getRelativeTo() {
return m_relativeTo;
}
/**
* Returns the resource.<p>
*
* @return the resource
*/
public CmsResource getResource() {
return m_resource;
}
/**
* Returns the resource type for the given resource.<p>
*
* @return the resource type for the given resource
*/
public I_CmsResourceType getResourceType() {
if (m_resourceType == null) {
m_resourceType = OpenCms.getResourceManager().getResourceType(m_resource);
}
return m_resourceType;
}
/**
* Returns the resource type id for the given resource.<p>
*
* @return the resource type id for the given resource
*/
public int getResourceTypeId() {
return getResourceType().getTypeId();
}
/**
* Returns the resource type name for the given resource.<p>
*
* @return the resource type name for the given resource
*/
public String getResourceTypeName() {
return getResourceType().getTypeName();
}
/**
* Returns the site of the current resources,
* taking into account the set site mode.<p>
*
* @return the site path
*/
public String getSite() {
String site = null;
if ((m_siteMode == SITE_MODE_MATCHING) || (m_cms == null)) {
site = OpenCms.getSiteManager().getSiteRoot(m_resource.getRootPath());
} else if (m_siteMode == SITE_MODE_CURRENT) {
site = m_cms.getRequestContext().getSiteRoot();
} else if (m_siteMode == SITE_MODE_ROOT) {
site = "";
}
return (site == null ? "" : site);
}
/**
* Returns the site mode.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @return the site mode
*/
public CmsResourceUtilSiteMode getSiteMode() {
return m_siteMode;
}
/**
* Returns the title of the site.<p>
*
* @return the title of the site
*/
public String getSiteTitle() {
String title = getSite();
String rootSite = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot("");
title = getCms().readPropertyObject(title, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue(title);
} catch (CmsException e) {
// ignore
} finally {
getCms().getRequestContext().setSiteRoot(rootSite);
}
return title;
}
/**
* Returns the size of the given resource as a String.<p>
*
* For directories it returns <code>SIZE_DIR</code>.<p>
*
* @return the size of the given resource as a String
*/
public String getSizeString() {
return m_resource.getLength() == -1 ? SIZE_DIR : "" + m_resource.getLength();
}
/**
* Returns resource state abbreviation.<p>
*
* @return resource state abbreviation
*/
public char getStateAbbreviation() {
return getResource().getState().getAbbreviation();
}
/**
* Returns the state name for a resource.<p>
*
* Uses default locale if request context is <code>null</code>.<p>
*
* @return the state name for that resource
*/
public String getStateName() {
CmsResourceState state = m_resource.getState();
String name;
if (m_request == null) {
name = org.opencms.workplace.explorer.Messages.get().getBundle().key(
org.opencms.workplace.explorer.Messages.getStateKey(state));
} else {
name = org.opencms.workplace.explorer.Messages.get().getBundle(m_request.getLocale()).key(
org.opencms.workplace.explorer.Messages.getStateKey(state));
}
return name;
}
/**
* Returns the style class to use for the given resource.<p>
*
* @return style class name
*
* @see org.opencms.workplace.list.CmsListExplorerColumn#getExplorerStyleDef()
*/
public String getStyleClassName() {
if (isInsideProject() && isEditable()) {
if (m_resource.getState().isChanged()) {
return "fc";
} else if (m_resource.getState().isNew()) {
return "fn";
} else if (m_resource.getState().isDeleted()) {
return "fd";
} else {
return "nf";
}
}
return "fp";
}
/**
* Returns additional style sheets for the resource type icon depending on siblings.<p>
*
* That is, depending on {@link CmsResource#getSiblingCount()}
*
* Use it with the {@link #getIconPathExplorer} method.<p>
*
* @return additional style sheets depending on siblings
*/
public String getStyleSiblings() {
StringBuffer style = new StringBuffer(128);
if (m_resource.getSiblingCount() > 1) {
style.append("background-image:url(");
style.append(CmsWorkplace.getSkinUri());
style.append(getIconPathResourceType());
style.append("); background-position: 0px 0px; background-repeat: no-repeat; ");
}
return style.toString();
}
/**
* Returns the system lock information tooltip for the explorer view.<p>
*
* @param forExplorer if the tool tip should be generated for the explorer view
*
* @return the system lock information tooltip
*/
public String getSystemLockInfo(boolean forExplorer) {
if (getLock().getSystemLock().isPublish()) {
if (!forExplorer) {
return getMessages().key(Messages.GUI_PUBLISH_TOOLTIP_0);
} else {
// see explorer.js(sysLockInfo) and top_js.jsp(publishlock)
return "p"; // should have length == 1
}
}
return "";
}
/**
* Returns additional style sheets depending on publication constraints.<p>
*
* That is, depending on {@link CmsResource#getDateReleased()} and
* {@link CmsResource#getDateExpired()}.<p>
*
* @return additional style sheets depending on publication constraints
*
* @see #getTimeWindowLayoutType()
*/
public String getTimeWindowLayoutStyle() {
return getTimeWindowLayoutType() == CmsResourceUtil.LAYOUTSTYLE_INRANGE ? "" : "font-style:italic;";
}
/**
* Returns the layout style for the current time window state.<p>
*
* <ul>
* <li><code>{@link CmsResourceUtil#LAYOUTSTYLE_INRANGE}</code>: The time window is in range
* <li><code>{@link CmsResourceUtil#LAYOUTSTYLE_BEFORERELEASE}</code>: The resource is not yet released
* <li><code>{@link CmsResourceUtil#LAYOUTSTYLE_AFTEREXPIRE}</code>: The resource has already expired
* </ul>
*
* @return the layout style for the current time window state
*
* @see #getTimeWindowLayoutStyle()
*/
public int getTimeWindowLayoutType() {
int layoutstyle = CmsResourceUtil.LAYOUTSTYLE_INRANGE;
if (!m_resource.isReleased(getCms().getRequestContext().getRequestTime())) {
layoutstyle = CmsResourceUtil.LAYOUTSTYLE_BEFORERELEASE;
} else if (m_resource.isExpired(getCms().getRequestContext().getRequestTime())) {
layoutstyle = CmsResourceUtil.LAYOUTSTYLE_AFTEREXPIRE;
}
return layoutstyle;
}
/**
* Returns the title of a resource.<p>
*
* @return the title for that resource
*/
public String getTitle() {
String title = "";
try {
title = getCms().readPropertyObject(
getCms().getSitePath(m_resource),
CmsPropertyDefinition.PROPERTY_TITLE,
false).getValue();
} catch (Throwable e) {
String storedSiteRoot = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot("");
title = getCms().readPropertyObject(
m_resource.getRootPath(),
CmsPropertyDefinition.PROPERTY_TITLE,
false).getValue();
} catch (Exception e1) {
// should usually never happen
if (LOG.isInfoEnabled()) {
LOG.info(e);
}
} finally {
getCms().getRequestContext().setSiteRoot(storedSiteRoot);
}
}
if (title == null) {
title = "";
}
return title;
}
/**
* Returns the name of the user who created the given resource.<p>
*
* @return the name of the user who created the given resource
*/
public String getUserCreated() {
String user = m_resource.getUserCreated().toString();
try {
user = getCurrentOuRelativeName(CmsPrincipal.readPrincipalIncludingHistory(
getCms(),
m_resource.getUserCreated()).getName());
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage());
}
return user;
}
/**
* Returns the name of the user who last modified the given resource.<p>
*
* @return the name of the user who last modified the given resource
*/
public String getUserLastModified() {
String user = m_resource.getUserLastModified().toString();
try {
user = getCurrentOuRelativeName(CmsPrincipal.readPrincipalIncludingHistory(
getCms(),
m_resource.getUserLastModified()).getName());
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage());
}
return user;
}
/**
* Returns <code>true</code> if the given resource is editable by the current user.<p>
*
* Returns <code>false</code> if no request context is set.<p>
*
* @return <code>true</code> if the given resource is editable by the current user
*/
public boolean isEditable() {
if (m_request == null) {
return false;
}
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(getResourceTypeName());
if (settings != null) {
String rightSite = OpenCms.getSiteManager().getSiteRoot(getResource().getRootPath());
if (rightSite == null) {
rightSite = "";
}
String currentSite = getCms().getRequestContext().getSiteRoot();
try {
getCms().getRequestContext().setSiteRoot(rightSite);
return settings.isEditable(getCms(), getResource());
} finally {
getCms().getRequestContext().setSiteRoot(currentSite);
}
}
return false;
}
/**
* Returns <code>true</code> if the given resource is in the reference project.<p>
*
* Returns <code>false</code> if the request context is <code>null</code>.<p>
*
* @return <code>true</code> if the given resource is in the reference project
*
* @see #getReferenceProject()
*/
public boolean isInsideProject() {
return CmsProject.isInsideProject(getProjectResources(), getResource());
}
/**
* Returns <code>true</code> if the stored resource has been released and has not expired.<p>
*
* If no request context is available, the current time is used for the validation check.<p>
*
* @return <code>true</code> if the stored resource has been released and has not expired
*
* @see CmsResource#isReleasedAndNotExpired(long)
*/
public boolean isReleasedAndNotExpired() {
long requestTime;
if (m_request == null) {
requestTime = System.currentTimeMillis();
} else {
requestTime = m_request.getRequestTime();
}
return m_resource.isReleasedAndNotExpired(requestTime);
}
/**
* Sets the path abbreviation length.<p>
*
* If greater than zero, the path will be formatted to this number of chars.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @param abbrevLength the path abbreviation length to set
*/
public void setAbbrevLength(int abbrevLength) {
m_abbrevLength = abbrevLength;
}
/**
* Sets the cms context.<p>
*
* @param cms the cms context to set
*/
public void setCms(CmsObject cms) {
m_cms = cms;
m_request = cms.getRequestContext();
m_referenceProject = null;
m_projectResources = null;
m_messages = null;
}
/**
* Sets the project to use to check project state.<p>
*
* @param project the project to set
*/
public void setReferenceProject(CmsProject project) {
m_referenceProject = project;
m_projectResources = null;
}
/**
* Sets the 'relative to' path.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @param relativeTo the 'relative to' path to set
*/
public void setRelativeTo(String relativeTo) {
m_relativeTo = relativeTo;
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_relativeTo)) {
m_relativeTo = null;
} else {
if (!m_relativeTo.startsWith("/")) {
m_relativeTo = "/" + m_relativeTo;
}
if (!m_relativeTo.endsWith("/")) {
m_relativeTo += "/";
}
}
}
/**
* Sets the resource.<p>
*
* @param resource the resource to set
*/
public void setResource(CmsResource resource) {
m_resource = resource;
m_lock = null;
m_resourceType = null;
}
/**
* Sets the site mode.<p>
*
* This only affects the generation of the path for the current resource.<p>
*
* @param siteMode the site mode to set
*/
public void setSiteMode(CmsResourceUtilSiteMode siteMode) {
m_siteMode = siteMode;
}
/**
* Returns the simple name if the ou is the same as the current user's ou.<p>
*
* @param name the fully qualified name to check
*
* @return the simple name if the ou is the same as the current user's ou
*/
private String getCurrentOuRelativeName(String name) {
if (m_request == null) {
return CmsOrganizationalUnit.SEPARATOR + name;
}
String ou = CmsOrganizationalUnit.getParentFqn(name);
if (ou.equals(m_request.currentUser().getOuFqn())) {
return CmsOrganizationalUnit.getSimpleName(name);
}
return CmsOrganizationalUnit.SEPARATOR + name;
}
/**
* Returns the message bundle for formatting dates, depends on the request locale.<p>
*
* @return the message bundle for formatting dates
*/
private CmsMessages getMessages() {
if (m_messages == null) {
if (m_request != null) {
m_messages = Messages.get().getBundle(m_request.getLocale());
} else {
m_messages = Messages.get().getBundle();
}
}
return m_messages;
}
/**
* Returns the reference project resources.<p>
*
* @return the reference project resources
*/
private List getProjectResources() {
if (m_projectResources == null) {
try {
m_projectResources = getCms().readProjectResources(getReferenceProject());
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
// use an empty list (all resources are "outside")
m_projectResources = new ArrayList();
}
}
return m_projectResources;
}
} | Fixed some issues with deleted users showing the id instead of the name in the GUI
| src/org/opencms/workplace/explorer/CmsResourceUtil.java | Fixed some issues with deleted users showing the id instead of the name in the GUI | <ide><path>rc/org/opencms/workplace/explorer/CmsResourceUtil.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/workplace/explorer/CmsResourceUtil.java,v $
<del> * Date : $Date: 2008/03/27 16:50:41 $
<del> * Version: $Revision: 1.13 $
<add> * Date : $Date: 2008/04/02 07:14:57 $
<add> * Version: $Revision: 1.14 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Management System
<ide> *
<ide> * @author Michael Moossen
<ide> *
<del> * @version $Revision: 1.13 $
<add> * @version $Revision: 1.14 $
<ide> *
<ide> * @since 6.0.0
<ide> */
<ide>
<ide> String lockedBy = "";
<ide> if (!getLock().isNullLock()) {
<add> // user
<add> lockedBy = getLock().getUserId().toString();
<ide> try {
<del> lockedBy = getCurrentOuRelativeName(getCms().readUser(getLock().getUserId()).getName());
<add> lockedBy = getCurrentOuRelativeName(CmsPrincipal.readPrincipalIncludingHistory(
<add> getCms(),
<add> getLock().getUserId()).getName());
<ide> } catch (Throwable e) {
<ide> lockedBy = e.getMessage();
<ide> } |
|
JavaScript | mit | 6d0ea0795888506f76fd0cce94c9f7c03ee11cd5 | 0 | pablopunk/chronocube,pablopunk/chronocube |
function Solve(name, times) {
this.name = name
this.times = times
}
function DataManager() {
this.solves = [] // array of Solve objects
this.numberOfSolves = 0 // solves loaded into the app !! not the actual number (solves.length)
this.currentSolve = 'Default' // @implement save and load currentSolve in localstorage
this.init = function() {
if(typeof(Storage) == "undefined") {
// Sorry! No Web Storage support..
Error.print('Sorry! No Web Storage support..');
}
if (typeof JSON === "undefined") {
Error.print('JSON not supported')
}
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
Error.print('Sorry, no html5 support in this browser')
}
document.getElementById('importFile').addEventListener("change", evt = function() {
Data.importTimes(evt)
});
document.getElementById('solve')
// load number of solves stored
this.numberOfSolves = localStorage.getItem('numberOfSolves')
if (this.numberOfSolves == null) this.numberOfSolves = 0
// load solves from storage
this.load()
this.refresh()
MainLayout.scrollDown()
}
this.load = function() {
if (this.numberOfSolves == 0) {
this.solves = [new Solve('Default', [])]
this.numberOfSolves = 1
this.currentSolve = 'Default'
}
else {
this.solves = JSON.parse(localStorage.getItem('solves')) // JSON object in localstorage
if (this.solves == null) this.solves = [new Solve('Default', [])]
this.currentSolve = localStorage['currentSolve']
if (this.currentSolve == null) this.currentSolve = 'Default'
}
}
this.save = function() {
if (this.solves == null) { // no solves
localStorage['numberOfSolves'] = 1
localStorage['solves'] = JSON.stringify([new Solve('Default', [])])
localStorage['currentSolve'] = 'Default'
} else {
localStorage['numberOfSolves'] = this.solves.length
localStorage['solves'] = JSON.stringify(this.solves)
localStorage['currentSolve'] = this.currentSolve
}
}
this.updateSolveName = function() {
var content = ''
for (i in this.solves) {
if (this.currentSolve == this.solves[i].name) content += '<option selected>'+this.solves[i].name+'</option>'
else content += '<option>'+this.solves[i].name+'</option>'
}
document.getElementById('solveNames').innerHTML = content
$('#solveNames').select2({
minimumResultsForSearch: Infinity,
theme: "classic"
});
}
this.changeSolve = function(index) {
this.currentSolve = this.solves[index].name
this.refresh()
$('#solveNames').select2("close");
}
this.getIndex = function(name) {
for (i in this.solves) {
if (this.solves[i].name == name) {
return i
}
}
}
this.add = function() {
var currentTime = document.getElementById("chronotime").innerHTML
this.solves[this.getIndex(this.currentSolve)].times.push(currentTime)
MainLayout.scrollDown()
}
this.refresh = function() {
if (this.solves.length == 0) return;
var best = this.getBestTime();
var table = '';
var times = this.solves[this.getIndex(this.currentSolve)].times
for (i=0; i<times.length; i++) {
if (i == best) {
table += '<tr style="color:#44ff77"><td>'+(parseInt(i)+1)+'</td><td>'+times[i]+'</td><td onclick="Data.deleteTime('+i+')">X</td></tr>';
} else {
table += '<tr><td>'+(parseInt(i)+1)+'</td><td>'+times[i]+'</td><td onclick="Data.deleteTime('+i+')">X</td></tr>';
}
}
document.getElementById('times-table').innerHTML = table
this.save()
this.updateSolveName()
if (times.length == 0) {
document.getElementById('best-solve').innerHTML = "Best: -"
document.getElementById('average-all').innerHTML = "Average All: -"
document.getElementById('average-5').innerHTML = "Average 5: -"
}
else {
// display scores
document.getElementById('best-solve').innerHTML = "Best: "+ times[best]
document.getElementById('average-all').innerHTML = "Average All: " + this.getAverageAll()
if (times.length>4) document.getElementById('average-5').innerHTML = "Average 5: " + this.getAverage5();
else document.getElementById('average-5').innerHTML = "Average 5: -"
}
}
this.deleteTime = function(index) {
this.solves[this.getIndex(this.currentSolve)].times.splice(parseInt(index), 1)
this.refresh();
}
this.saveBackground = function() {
localStorage['bgIndex'] = (""+MainLayout.backgroundSelected)
}
this.restoreBackground = function() {
return ( (localStorage.getItem('bgIndex') == 'undefined' || isNaN(localStorage.getItem('bgIndex'))) ? 0 : parseInt(localStorage.getItem('bgIndex')) )
}
// index of the best time in the array
this.getBestTime = function() {
var times = this.solves[this.getIndex(this.currentSolve)].times
var best = 0; // index 0
var i = 1;
for (i=1; i<times.length; i++) {
var old = this.getIntFromTimeString(times[best])
var cur = this.getIntFromTimeString(times[i])
if (cur < old) best = i;
}
return best;
}
this.getAverageAll = function() {
var times = this.solves[this.getIndex(this.currentSolve)].times
var i=0, average=0, min=0, sec=0, dec=0;
for (i=0; i<times.length; i++) {
min = parseInt(times[i].charAt(0)+times[i].charAt(1))
sec = parseInt(times[i].charAt(3)+times[i].charAt(4))
dec = parseInt(times[i].charAt(6)+times[i].charAt(7))
// average in decimals
average += ( (min*60*100) + (sec*100) + dec)
}
average /= times.length
average = average.toFixed(0);
return this.getAverageStringFromDec(average)
}
this.getAverage5 = function() {
var times = this.solves[this.getIndex(this.currentSolve)].times
var i=0, average=0, min=0, sec=0, dec=0;
times = times.slice(times.length-5, times.length)
times.sort()
for (i=1; i<times.length-1; i++) {
// @debug
console.log('time'+i+": "+times[i])
min = parseInt(times[i].charAt(0)+times[i].charAt(1))
sec = parseInt(times[i].charAt(3)+times[i].charAt(4))
dec = parseInt(times[i].charAt(6)+times[i].charAt(7))
// average in decimals
average += ( (min*60*100) + (sec*100) + dec)
}
average /= 3
average = average.toFixed(0);
return this.getAverageStringFromDec(average)
}
this.getAverageStringFromDec = function(dec) {
var decString = ""+dec;
var l = decString.length;
var decimals = decString.charAt(l-2) + decString.charAt(l-1) // last two digits
if (dec < 100) {
return "00:00:"+dec
} // else
if (dec < 6000) {
var seconds = (dec < 1000 ? "0" + decString.charAt(0) : decString.charAt(0)+decString.charAt(1))
return "00:" + seconds + ":" + decimals
} // else
var minutes = Math.floor(dec / 6000);
var seconds = ((dec % 6000) / 100).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds + ":" + decimals;
}
this.getIntFromTimeString = function(time) {
var r = time.replace(/:/g, ''); // removes ':'
return parseInt(r);
}
this.downloadtxt = function() {
alert("This feature will be available soon :)")
//this.exportTimesToTxt() @implement with the new objects
MainLayout.hideDownloadOptions()
}
this.downloadcsv = function() {
alert("This feature will be available soon :)")
//this.exportTimesToCsv() @implement with the new objects
MainLayout.hideDownloadOptions()
}
this.exportTimesToCsv = function() {
if (this.savedTimes.length==0) {
Error.print('No solves yet')
return;
}
var csvContent = "data:text/csv;charset=utf-8,";
var i = 0;
csvContent += "All solves;Average All"+(this.savedTimes.length>4 ? ";Average 5\n" : "\n")
csvContent += this.savedTimes[i]+";"+this.getAverageAll()+(this.savedTimes.length>4 ? ";"+this.getAverage5()+"\n" : "\n")
for (i=1; i<this.savedTimes.length;i++) {
csvContent += this.savedTimes.length ? this.savedTimes[i] + "\n" : this.savedTimes[i];
}
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
}
this.exportTimesToTxt = function() {
if (this.savedTimes.length==0) {
Error.print('No solves yet')
return;
}
var csvContent = "data:text/txt;charset=utf-8,";
var i = 0;
csvContent += "All solves\tAverage All"+(this.savedTimes.length>4 ? "\tAverage 5\n" : "\n")
csvContent += this.savedTimes[i]+"\t"+this.getAverageAll()+(this.savedTimes.length>4 ? "\t"+this.getAverage5()+"\n" : "\n")
for (i=1; i<this.savedTimes.length;i++) {
csvContent += this.savedTimes.length ? this.savedTimes[i] + "\n" : this.savedTimes[i];
}
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
}
this.importTimes = function(evt) {
alert("This feature will be available soon :)")
}
this.newSolve = function(name) {
this.currentSolve = name
this.solves.push(new Solve(name, []))
this.refresh()
}
}
| js/Data.js |
function Solve(name, times) {
this.name = name
this.times = times
}
function DataManager() {
this.solves = [] // array of Solve objects
this.numberOfSolves = 0 // solves loaded into the app !! not the actual number (solves.length)
this.currentSolve = 'Default' // @implement save and load currentSolve in localstorage
this.init = function() {
if(typeof(Storage) == "undefined") {
// Sorry! No Web Storage support..
Error.print('Sorry! No Web Storage support..');
}
if (typeof JSON === "undefined") {
Error.print('JSON not supported')
}
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
Error.print('Sorry, no html5 support in this browser')
}
document.getElementById('importFile').addEventListener("change", evt = function() {
Data.importTimes(evt)
});
document.getElementById('solve')
// load number of solves stored
this.numberOfSolves = localStorage.getItem('numberOfSolves')
if (this.numberOfSolves == null) this.numberOfSolves = 0
// load solves from storage
this.load()
this.refresh()
MainLayout.scrollDown()
}
this.load = function() {
if (this.numberOfSolves == 0) {
this.solves = [new Solve('Default', [])]
this.numberOfSolves = 1
this.currentSolve = 'Default'
}
else {
this.solves = JSON.parse(localStorage.getItem('solves')) // JSON object in localstorage
if (this.solves == null) this.solves = [new Solve('Default', [])]
this.currentSolve = localStorage['currentSolve']
if (this.currentSolve == null) this.currentSolve = 'Default'
}
}
this.save = function() {
if (this.solves == null) { // no solves
localStorage['numberOfSolves'] = 1
localStorage['solves'] = JSON.stringify([new Solve('Default', [])])
localStorage['currentSolve'] = 'Default'
} else {
localStorage['numberOfSolves'] = this.solves.length
localStorage['solves'] = JSON.stringify(this.solves)
localStorage['currentSolve'] = this.currentSolve
}
}
this.updateSolveName = function() {
var content = ''
for (i in this.solves) {
if (this.currentSolve == this.solves[i].name) content += '<option selected>'+this.solves[i].name+'</option>'
else content += '<option>'+this.solves[i].name+'</option>'
}
document.getElementById('solveNames').innerHTML = content
$('#solveNames').select2({
minimumResultsForSearch: Infinity,
theme: "classic"
});
}
this.changeSolve = function(index) {
this.currentSolve = this.solves[index].name
this.refresh()
$('#solveNames').select2("close");
}
this.getIndex = function(name) {
for (i in this.solves) {
if (this.solves[i].name == name) {
return i
}
}
}
this.add = function() {
var currentTime = document.getElementById("chronotime").innerHTML
this.solves[this.getIndex(this.currentSolve)].times.push(currentTime)
MainLayout.scrollDown()
}
this.refresh = function() {
if (this.solves.length == 0) return;
var best = this.getBestTime();
var table = '';
var times = this.solves[this.getIndex(this.currentSolve)].times
for (i=0; i<times.length; i++) {
if (i == best) {
table += '<tr style="color:#44ff77"><td>'+(parseInt(i)+1)+'</td><td>'+times[i]+'</td><td onclick="Data.deleteTime('+i+')">X</td></tr>';
} else {
table += '<tr><td>'+(parseInt(i)+1)+'</td><td>'+times[i]+'</td><td onclick="Data.deleteTime('+i+')">X</td></tr>';
}
}
document.getElementById('times-table').innerHTML = table
this.save()
this.updateSolveName()
if (times.length == 0) {
document.getElementById('best-solve').innerHTML = "Best: -"
document.getElementById('average-all').innerHTML = "Average All: -"
document.getElementById('average-5').innerHTML = "Average 5: -"
}
else {
// display scores
document.getElementById('best-solve').innerHTML = "Best: "+ times[best]
document.getElementById('average-all').innerHTML = "Average All: " + this.getAverage(times.length)
if (times.length>4) document.getElementById('average-5').innerHTML = "Average 5: " + this.getAverage(5);
else document.getElementById('average-5').innerHTML = "Average 5: -"
}
}
this.deleteTime = function(index) {
this.solves[this.getIndex(this.currentSolve)].times.splice(parseInt(index), 1)
this.refresh();
}
this.saveBackground = function() {
localStorage['bgIndex'] = (""+MainLayout.backgroundSelected)
}
this.restoreBackground = function() {
return ( (localStorage.getItem('bgIndex') == 'undefined' || isNaN(localStorage.getItem('bgIndex'))) ? 0 : parseInt(localStorage.getItem('bgIndex')) )
}
// index of the best time in the array
this.getBestTime = function() {
var times = this.solves[this.getIndex(this.currentSolve)].times
var best = 0; // index 0
var i = 1;
for (i=1; i<times.length; i++) {
var old = this.getIntFromTimeString(times[best])
var cur = this.getIntFromTimeString(times[i])
if (cur < old) best = i;
}
return best;
}
// get average of last 'size' solves -> if size==average.length, then it returns all solves average
this.getAverage = function(size) {
var times = this.solves[this.getIndex(this.currentSolve)].times
var i=0, average=0, min=0, sec=0, dec=0;
for (i=times.length-size; i<times.length; i++) {
min = parseInt(times[i].charAt(0)+times[i].charAt(1))
sec = parseInt(times[i].charAt(3)+times[i].charAt(4))
dec = parseInt(times[i].charAt(6)+times[i].charAt(7))
// average in decimals
average += ( (min*60*100) + (sec*100) + dec)
}
average /= size
average = average.toFixed(0);
return this.getAverageStringFromDec(average)
}
this.getAverageStringFromDec = function(dec) {
var decString = ""+dec;
var l = decString.length;
var decimals = decString.charAt(l-2) + decString.charAt(l-1) // last two digits
if (dec < 100) {
return "00:00:"+dec
} // else
if (dec < 6000) {
var seconds = (dec < 1000 ? "0" + decString.charAt(0) : decString.charAt(0)+decString.charAt(1))
return "00:" + seconds + ":" + decimals
} // else
var minutes = Math.floor(dec / 6000);
var seconds = ((dec % 6000) / 100).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds + ":" + decimals;
}
this.getIntFromTimeString = function(time) {
var r = time.replace(/:/g, ''); // removes ':'
return parseInt(r);
}
this.downloadtxt = function() {
alert("This feature will be available soon :)")
//this.exportTimesToTxt() @implement with the new objects
MainLayout.hideDownloadOptions()
}
this.downloadcsv = function() {
alert("This feature will be available soon :)")
//this.exportTimesToCsv() @implement with the new objects
MainLayout.hideDownloadOptions()
}
this.exportTimesToCsv = function() {
if (this.savedTimes.length==0) {
Error.print('No solves yet')
return;
}
var csvContent = "data:text/csv;charset=utf-8,";
var i = 0;
csvContent += "All solves;Average All"+(this.savedTimes.length>4 ? ";Average 5\n" : "\n")
csvContent += this.savedTimes[i]+";"+this.getAverage(this.savedTimes.length)+(this.savedTimes.length>4 ? ";"+this.getAverage(5)+"\n" : "\n")
for (i=1; i<this.savedTimes.length;i++) {
csvContent += this.savedTimes.length ? this.savedTimes[i] + "\n" : this.savedTimes[i];
}
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
}
this.exportTimesToTxt = function() {
if (this.savedTimes.length==0) {
Error.print('No solves yet')
return;
}
var csvContent = "data:text/txt;charset=utf-8,";
var i = 0;
csvContent += "All solves\tAverage All"+(this.savedTimes.length>4 ? "\tAverage 5\n" : "\n")
csvContent += this.savedTimes[i]+"\t"+this.getAverage(this.savedTimes.length)+(this.savedTimes.length>4 ? "\t"+this.getAverage(5)+"\n" : "\n")
for (i=1; i<this.savedTimes.length;i++) {
csvContent += this.savedTimes.length ? this.savedTimes[i] + "\n" : this.savedTimes[i];
}
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
}
this.importTimes = function(evt) {
alert("This feature will be available soon :)")
}
this.newSolve = function(name) {
this.currentSolve = name
this.solves.push(new Solve(name, []))
this.refresh()
}
}
| average of 5 trims the best and worst solve (of last 5)
| js/Data.js | average of 5 trims the best and worst solve (of last 5) | <ide><path>s/Data.js
<ide> else {
<ide> // display scores
<ide> document.getElementById('best-solve').innerHTML = "Best: "+ times[best]
<del> document.getElementById('average-all').innerHTML = "Average All: " + this.getAverage(times.length)
<del> if (times.length>4) document.getElementById('average-5').innerHTML = "Average 5: " + this.getAverage(5);
<add> document.getElementById('average-all').innerHTML = "Average All: " + this.getAverageAll()
<add> if (times.length>4) document.getElementById('average-5').innerHTML = "Average 5: " + this.getAverage5();
<ide> else document.getElementById('average-5').innerHTML = "Average 5: -"
<ide> }
<ide> }
<ide> return best;
<ide> }
<ide>
<del> // get average of last 'size' solves -> if size==average.length, then it returns all solves average
<del> this.getAverage = function(size) {
<add> this.getAverageAll = function() {
<ide> var times = this.solves[this.getIndex(this.currentSolve)].times
<ide> var i=0, average=0, min=0, sec=0, dec=0;
<del> for (i=times.length-size; i<times.length; i++) {
<add> for (i=0; i<times.length; i++) {
<ide> min = parseInt(times[i].charAt(0)+times[i].charAt(1))
<ide> sec = parseInt(times[i].charAt(3)+times[i].charAt(4))
<ide> dec = parseInt(times[i].charAt(6)+times[i].charAt(7))
<ide> // average in decimals
<ide> average += ( (min*60*100) + (sec*100) + dec)
<ide> }
<del> average /= size
<add> average /= times.length
<add> average = average.toFixed(0);
<add>
<add> return this.getAverageStringFromDec(average)
<add> }
<add>
<add> this.getAverage5 = function() {
<add> var times = this.solves[this.getIndex(this.currentSolve)].times
<add> var i=0, average=0, min=0, sec=0, dec=0;
<add> times = times.slice(times.length-5, times.length)
<add> times.sort()
<add> for (i=1; i<times.length-1; i++) {
<add> // @debug
<add> console.log('time'+i+": "+times[i])
<add> min = parseInt(times[i].charAt(0)+times[i].charAt(1))
<add> sec = parseInt(times[i].charAt(3)+times[i].charAt(4))
<add> dec = parseInt(times[i].charAt(6)+times[i].charAt(7))
<add> // average in decimals
<add> average += ( (min*60*100) + (sec*100) + dec)
<add> }
<add> average /= 3
<ide> average = average.toFixed(0);
<ide>
<ide> return this.getAverageStringFromDec(average)
<ide> var i = 0;
<ide>
<ide> csvContent += "All solves;Average All"+(this.savedTimes.length>4 ? ";Average 5\n" : "\n")
<del> csvContent += this.savedTimes[i]+";"+this.getAverage(this.savedTimes.length)+(this.savedTimes.length>4 ? ";"+this.getAverage(5)+"\n" : "\n")
<add> csvContent += this.savedTimes[i]+";"+this.getAverageAll()+(this.savedTimes.length>4 ? ";"+this.getAverage5()+"\n" : "\n")
<ide> for (i=1; i<this.savedTimes.length;i++) {
<ide> csvContent += this.savedTimes.length ? this.savedTimes[i] + "\n" : this.savedTimes[i];
<ide> }
<ide> var i = 0;
<ide>
<ide> csvContent += "All solves\tAverage All"+(this.savedTimes.length>4 ? "\tAverage 5\n" : "\n")
<del> csvContent += this.savedTimes[i]+"\t"+this.getAverage(this.savedTimes.length)+(this.savedTimes.length>4 ? "\t"+this.getAverage(5)+"\n" : "\n")
<add> csvContent += this.savedTimes[i]+"\t"+this.getAverageAll()+(this.savedTimes.length>4 ? "\t"+this.getAverage5()+"\n" : "\n")
<ide> for (i=1; i<this.savedTimes.length;i++) {
<ide> csvContent += this.savedTimes.length ? this.savedTimes[i] + "\n" : this.savedTimes[i];
<ide> } |
|
Java | apache-2.0 | e0bca445af7c8b3f8867a30e6d664c5a421de594 | 0 | robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,gstevey/gradle,gradle/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,gradle/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,lsmaira/gradle,lsmaira/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.initialization;
import org.gradle.api.internal.initialization.loadercache.ClassLoaderCache;
import org.gradle.api.internal.initialization.loadercache.ClassLoaderId;
import org.gradle.internal.classloader.CachingClassLoader;
import org.gradle.internal.classloader.MultiParentClassLoader;
import org.gradle.internal.classpath.ClassPath;
import java.util.ArrayList;
import java.util.List;
public class DefaultClassLoaderScope extends AbstractClassLoaderScope {
public static final String STRICT_MODE_PROPERTY = "org.gradle.classloaderscope.strict";
private final ClassLoaderScope parent;
private boolean locked;
private ClassPath export = ClassPath.EMPTY;
private List<ClassLoader> exportLoaders; // if not null, is not empty
private ClassPath local = ClassPath.EMPTY;
private List<ClassLoader> ownLoaders;
// If these are not null, we are pessimistic (loaders asked for before locking)
private MultiParentClassLoader exportingClassLoader;
private MultiParentClassLoader localClassLoader;
// What is actually exposed
private ClassLoader effectiveLocalClassLoader;
private ClassLoader effectiveExportClassLoader;
public DefaultClassLoaderScope(ClassLoaderScopeIdentifier id, ClassLoaderScope parent, ClassLoaderCache classLoaderCache) {
super(id, classLoaderCache);
this.parent = parent;
}
private ClassLoader buildLockedLoader(ClassLoaderId id, ClassPath classPath) {
if (classPath.isEmpty()) {
return parent.getExportClassLoader();
}
return loader(id, classPath);
}
private ClassLoader buildLockedLoader(ClassLoaderId id, ClassLoader additional, ClassPath classPath) {
if (classPath.isEmpty()) {
return additional;
}
return new CachingClassLoader(new MultiParentClassLoader(additional, loader(id, classPath)));
}
private ClassLoader buildLockedLoader(ClassLoaderId id, ClassPath classPath, List<ClassLoader> loaders) {
if (loaders != null) {
return new CachingClassLoader(buildMultiLoader(id, classPath, loaders));
}
return buildLockedLoader(id, classPath);
}
private MultiParentClassLoader buildMultiLoader(ClassLoaderId id, ClassPath classPath, List<ClassLoader> loaders) {
int numParents = 1;
if (loaders != null) {
numParents += loaders.size();
}
if (!classPath.isEmpty()) {
numParents += 1;
}
List<ClassLoader> parents = new ArrayList<ClassLoader>(numParents);
parents.add(parent.getExportClassLoader());
if (loaders != null) {
parents.addAll(loaders);
}
if (!classPath.isEmpty()) {
parents.add(loader(id, classPath));
}
return new MultiParentClassLoader(parents);
}
private void buildEffectiveLoaders() {
if (effectiveLocalClassLoader == null) {
boolean hasExports = !export.isEmpty() || exportLoaders != null;
boolean hasLocals = !local.isEmpty();
if (locked) {
if (hasExports && hasLocals) {
effectiveExportClassLoader = buildLockedLoader(id.exportId(), export, exportLoaders);
effectiveLocalClassLoader = buildLockedLoader(id.localId(), effectiveExportClassLoader, local);
} else if (hasLocals) {
classLoaderCache.remove(id.exportId());
effectiveLocalClassLoader = buildLockedLoader(id.localId(), local);
effectiveExportClassLoader = parent.getExportClassLoader();
} else if (hasExports) {
classLoaderCache.remove(id.localId());
effectiveLocalClassLoader = buildLockedLoader(id.exportId(), export, exportLoaders);
effectiveExportClassLoader = effectiveLocalClassLoader;
} else {
classLoaderCache.remove(id.localId());
classLoaderCache.remove(id.exportId());
effectiveLocalClassLoader = parent.getExportClassLoader();
effectiveExportClassLoader = parent.getExportClassLoader();
}
} else { // creating before locking, have to create the most flexible setup
if (Boolean.getBoolean(STRICT_MODE_PROPERTY)) {
throw new IllegalStateException("Attempt to define scope class loader before scope is locked");
}
exportingClassLoader = buildMultiLoader(id.exportId(), export, exportLoaders);
effectiveExportClassLoader = new CachingClassLoader(exportingClassLoader);
localClassLoader = new MultiParentClassLoader(effectiveExportClassLoader, loader(id.localId(), local));
effectiveLocalClassLoader = new CachingClassLoader(localClassLoader);
}
export = null;
exportLoaders = null;
local = null;
}
}
@Override
public ClassLoader getExportClassLoader() {
buildEffectiveLoaders();
return effectiveExportClassLoader;
}
@Override
public ClassLoader getLocalClassLoader() {
buildEffectiveLoaders();
return effectiveLocalClassLoader;
}
@Override
public ClassLoaderScope getParent() {
return parent;
}
@Override
public boolean defines(Class<?> clazz) {
if (ownLoaders != null) {
for (ClassLoader ownLoader : ownLoaders) {
if (ownLoader.equals(clazz.getClassLoader())) {
return true;
}
}
}
return false;
}
private ClassLoader loader(ClassLoaderId id, ClassPath classPath) {
ClassLoader classLoader = classLoaderCache.get(id, classPath, parent.getExportClassLoader(), null);
if (ownLoaders == null) {
ownLoaders = new ArrayList<ClassLoader>();
}
ownLoaders.add(classLoader);
return classLoader;
}
@Override
public ClassLoaderScope local(ClassPath classPath) {
if (classPath.isEmpty()) {
return this;
}
assertNotLocked();
if (localClassLoader != null) {
ClassLoader loader = loader(id.localId(), classPath);
localClassLoader.addParent(loader);
} else {
local = local.plus(classPath);
}
return this;
}
@Override
public ClassLoaderScope export(ClassPath classPath) {
if (classPath.isEmpty()) {
return this;
}
assertNotLocked();
if (exportingClassLoader != null) {
exportingClassLoader.addParent(loader(id.exportId(), classPath));
} else {
export = export.plus(classPath);
}
return this;
}
@Override
public ClassLoaderScope export(ClassLoader classLoader) {
assertNotLocked();
if (exportingClassLoader != null) {
exportingClassLoader.addParent(classLoader);
} else {
if (exportLoaders == null) {
exportLoaders = new ArrayList<ClassLoader>(1);
}
exportLoaders.add(classLoader);
}
return this;
}
private void assertNotLocked() {
if (locked) {
throw new IllegalStateException("class loader scope is locked");
}
}
@Override
public ClassLoaderScope lock() {
locked = true;
return this;
}
@Override
public boolean isLocked() {
return locked;
}
}
| subprojects/core/src/main/java/org/gradle/api/internal/initialization/DefaultClassLoaderScope.java | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.initialization;
import org.gradle.api.internal.initialization.loadercache.ClassLoaderCache;
import org.gradle.api.internal.initialization.loadercache.ClassLoaderId;
import org.gradle.internal.classloader.CachingClassLoader;
import org.gradle.internal.classloader.MultiParentClassLoader;
import org.gradle.internal.classpath.ClassPath;
import java.util.ArrayList;
import java.util.List;
public class DefaultClassLoaderScope extends AbstractClassLoaderScope {
public static final String STRICT_MODE_PROPERTY = "org.gradle.classloaderscope.strict";
private final ClassLoaderScope parent;
private boolean locked;
private ClassPath export = ClassPath.EMPTY;
private List<ClassLoader> exportLoaders; // if not null, is not empty
private ClassPath local = ClassPath.EMPTY;
private List<ClassLoader> ownLoaders;
// If these are not null, we are pessimistic (loaders asked for before locking)
private MultiParentClassLoader exportingClassLoader;
private MultiParentClassLoader localClassLoader;
// What is actually exposed
private ClassLoader effectiveLocalClassLoader;
private ClassLoader effectiveExportClassLoader;
public DefaultClassLoaderScope(ClassLoaderScopeIdentifier id, ClassLoaderScope parent, ClassLoaderCache classLoaderCache) {
super(id, classLoaderCache);
this.parent = parent;
}
private ClassLoader buildLockedLoader(ClassLoaderId id, ClassPath classPath) {
if (classPath.isEmpty()) {
return parent.getExportClassLoader();
}
return loader(id, classPath);
}
private ClassLoader buildLockedLoader(ClassLoaderId id, ClassLoader additional, ClassPath classPath) {
if (classPath.isEmpty()) {
return additional;
}
return new CachingClassLoader(new MultiParentClassLoader(additional, loader(id, classPath)));
}
private ClassLoader buildLockedLoader(ClassLoaderId id, ClassPath classPath, List<ClassLoader> loaders) {
if (loaders != null) {
return new CachingClassLoader(buildMultiLoader(id, classPath, loaders));
} else if (!classPath.isEmpty()) {
return buildLockedLoader(id, classPath);
} else {
return parent.getExportClassLoader();
}
}
private MultiParentClassLoader buildMultiLoader(ClassLoaderId id, ClassPath classPath, List<ClassLoader> loaders) {
int numParents = 1;
if (loaders != null) {
numParents += loaders.size();
}
if (!classPath.isEmpty()) {
numParents += 1;
}
List<ClassLoader> parents = new ArrayList<ClassLoader>(numParents);
parents.add(parent.getExportClassLoader());
if (loaders != null) {
parents.addAll(loaders);
}
if (!classPath.isEmpty()) {
parents.add(loader(id, classPath));
}
return new MultiParentClassLoader(parents);
}
private void buildEffectiveLoaders() {
if (effectiveLocalClassLoader == null) {
boolean hasExports = !export.isEmpty() || exportLoaders != null;
boolean hasLocals = !local.isEmpty();
if (locked) {
if (hasExports && hasLocals) {
effectiveExportClassLoader = buildLockedLoader(id.exportId(), export, exportLoaders);
effectiveLocalClassLoader = buildLockedLoader(id.localId(), effectiveExportClassLoader, local);
} else if (hasLocals) {
classLoaderCache.remove(id.exportId());
effectiveLocalClassLoader = buildLockedLoader(id.localId(), local);
effectiveExportClassLoader = parent.getExportClassLoader();
} else if (hasExports) {
classLoaderCache.remove(id.localId());
effectiveLocalClassLoader = buildLockedLoader(id.exportId(), export, exportLoaders);
effectiveExportClassLoader = effectiveLocalClassLoader;
} else {
classLoaderCache.remove(id.localId());
classLoaderCache.remove(id.exportId());
effectiveLocalClassLoader = parent.getExportClassLoader();
effectiveExportClassLoader = parent.getExportClassLoader();
}
} else { // creating before locking, have to create the most flexible setup
if (Boolean.getBoolean(STRICT_MODE_PROPERTY)) {
throw new IllegalStateException("Attempt to define scope class loader before scope is locked");
}
exportingClassLoader = buildMultiLoader(id.exportId(), export, exportLoaders);
effectiveExportClassLoader = new CachingClassLoader(exportingClassLoader);
localClassLoader = new MultiParentClassLoader(effectiveExportClassLoader, loader(id.localId(), local));
effectiveLocalClassLoader = new CachingClassLoader(localClassLoader);
}
export = null;
exportLoaders = null;
local = null;
}
}
@Override
public ClassLoader getExportClassLoader() {
buildEffectiveLoaders();
return effectiveExportClassLoader;
}
@Override
public ClassLoader getLocalClassLoader() {
buildEffectiveLoaders();
return effectiveLocalClassLoader;
}
@Override
public ClassLoaderScope getParent() {
return parent;
}
@Override
public boolean defines(Class<?> clazz) {
if (ownLoaders != null) {
for (ClassLoader ownLoader : ownLoaders) {
if (ownLoader.equals(clazz.getClassLoader())) {
return true;
}
}
}
return false;
}
private ClassLoader loader(ClassLoaderId id, ClassPath classPath) {
ClassLoader classLoader = classLoaderCache.get(id, classPath, parent.getExportClassLoader(), null);
if (ownLoaders == null) {
ownLoaders = new ArrayList<ClassLoader>();
}
ownLoaders.add(classLoader);
return classLoader;
}
@Override
public ClassLoaderScope local(ClassPath classPath) {
if (classPath.isEmpty()) {
return this;
}
assertNotLocked();
if (localClassLoader != null) {
ClassLoader loader = loader(id.localId(), classPath);
localClassLoader.addParent(loader);
} else {
local = local.plus(classPath);
}
return this;
}
@Override
public ClassLoaderScope export(ClassPath classPath) {
if (classPath.isEmpty()) {
return this;
}
assertNotLocked();
if (exportingClassLoader != null) {
exportingClassLoader.addParent(loader(id.exportId(), classPath));
} else {
export = export.plus(classPath);
}
return this;
}
@Override
public ClassLoaderScope export(ClassLoader classLoader) {
assertNotLocked();
if (exportingClassLoader != null) {
exportingClassLoader.addParent(classLoader);
} else {
if (exportLoaders == null) {
exportLoaders = new ArrayList<ClassLoader>(1);
}
exportLoaders.add(classLoader);
}
return this;
}
private void assertNotLocked() {
if (locked) {
throw new IllegalStateException("class loader scope is locked");
}
}
@Override
public ClassLoaderScope lock() {
locked = true;
return this;
}
@Override
public boolean isLocked() {
return locked;
}
}
| Polish `DefaultClassLoaderScope`
- Remove redundant branch (`buildLockedLoader(id, classPath)` already
checks if the given `ClassPath` is empty
| subprojects/core/src/main/java/org/gradle/api/internal/initialization/DefaultClassLoaderScope.java | Polish `DefaultClassLoaderScope` | <ide><path>ubprojects/core/src/main/java/org/gradle/api/internal/initialization/DefaultClassLoaderScope.java
<ide> private ClassLoader buildLockedLoader(ClassLoaderId id, ClassPath classPath, List<ClassLoader> loaders) {
<ide> if (loaders != null) {
<ide> return new CachingClassLoader(buildMultiLoader(id, classPath, loaders));
<del> } else if (!classPath.isEmpty()) {
<del> return buildLockedLoader(id, classPath);
<del> } else {
<del> return parent.getExportClassLoader();
<del> }
<add> }
<add> return buildLockedLoader(id, classPath);
<ide> }
<ide>
<ide> private MultiParentClassLoader buildMultiLoader(ClassLoaderId id, ClassPath classPath, List<ClassLoader> loaders) { |
|
Java | mit | 09bccf320c777e27b9e6a821ad3dcc417a311455 | 0 | gurkenlabs/litiengine,gurkenlabs/litiengine | package de.gurkenlabs.litiengine;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlEnumValue;
import de.gurkenlabs.litiengine.util.MathUtilities;
/**
* The enum {@code Valign} defines a range of vertical alignments.
*/
@XmlEnum
public enum Valign {
@XmlEnumValue("bottom")
DOWN(1f),
@XmlEnumValue("middle")
MIDDLE(0.5f),
@XmlEnumValue("top")
TOP(0f),
MIDDLE_TOP(0.25f),
MIDDLE_DOWN(0.75f);
private final float portion;
Valign(float portion) {
this.portion = portion;
}
/**
* Gets the vertical align enumeration value for the specified string.
*
* @param valignString The string representing the enum value.
* @return The enum value represented by the specified string or {@link Valign#DOWN} if the specified string is invalid.
*/
public static Valign get(final String valignString) {
if (valignString == null || valignString.isEmpty()) {
return Valign.DOWN;
}
try {
return Valign.valueOf(valignString.toUpperCase());
} catch (final IllegalArgumentException iae) {
return Valign.DOWN;
}
}
/**
* Gets the proportional value of this instance.
*
* @param height The height to calculate the relative value from.
* @return The proportional value for the specified height.
*/
public float getValue(float height) {
return height * this.portion;
}
/**
* Gets the proportional value of this instance.
*
* @param height The height to calculate the relative value from.
* @return The proportional value for the specified height.
*/
public double getValue(double height) {
return height * this.portion;
}
/**
* Gets the proportional value of this instance.
*
* @param height The height to calculate the relative value from.
* @return The proportional value for the specified height.
*/
public int getValue(int height) {
return (int) (height * this.portion);
}
/**
* Gets the location for the specified object height to be vertically aligned within the bounds of the specified height.
*
* @param height The height, limiting the vertical alignment.
* @param objectHeight The height of the object for which to calculate the vertically aligned location.
* @return The y-coordinate for the location of the object with the specified height.
*/
public double getLocation(final double height, final double objectHeight) {
double value = this.getValue(height);
double location = value - objectHeight / 2.0;
if (objectHeight > height) {
return location;
}
return MathUtilities.clamp(location, 0, height - objectHeight);
}
}
| core/src/main/java/de/gurkenlabs/litiengine/Valign.java | package de.gurkenlabs.litiengine;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlEnumValue;
import de.gurkenlabs.litiengine.util.MathUtilities;
/**
* The enum {@code Valign} defines a range of vertical alignments.
*/
@XmlEnum
public enum Valign {
@XmlEnumValue("bottom")
DOWN(1f),
@XmlEnumValue("center")
MIDDLE(0.5f),
@XmlEnumValue("top")
TOP(0f),
MIDDLE_TOP(0.25f),
MIDDLE_DOWN(0.75f);
private final float portion;
Valign(float portion) {
this.portion = portion;
}
/**
* Gets the vertical align enumeration value for the specified string.
*
* @param valignString The string representing the enum value.
* @return The enum value represented by the specified string or {@link Valign#DOWN} if the specified string is invalid.
*/
public static Valign get(final String valignString) {
if (valignString == null || valignString.isEmpty()) {
return Valign.DOWN;
}
try {
return Valign.valueOf(valignString.toUpperCase());
} catch (final IllegalArgumentException iae) {
return Valign.DOWN;
}
}
/**
* Gets the proportional value of this instance.
*
* @param height The height to calculate the relative value from.
* @return The proportional value for the specified height.
*/
public float getValue(float height) {
return height * this.portion;
}
/**
* Gets the proportional value of this instance.
*
* @param height The height to calculate the relative value from.
* @return The proportional value for the specified height.
*/
public double getValue(double height) {
return height * this.portion;
}
/**
* Gets the proportional value of this instance.
*
* @param height The height to calculate the relative value from.
* @return The proportional value for the specified height.
*/
public int getValue(int height) {
return (int) (height * this.portion);
}
/**
* Gets the location for the specified object height to be vertically aligned within the bounds of the specified height.
*
* @param height The height, limiting the vertical alignment.
* @param objectHeight The height of the object for which to calculate the vertically aligned location.
* @return The y-coordinate for the location of the object with the specified height.
*/
public double getLocation(final double height, final double objectHeight) {
double value = this.getValue(height);
double location = value - objectHeight / 2.0;
if (objectHeight > height) {
return location;
}
return MathUtilities.clamp(location, 0, height - objectHeight);
}
}
| Keep Valign xml names consistent with enum names.
| core/src/main/java/de/gurkenlabs/litiengine/Valign.java | Keep Valign xml names consistent with enum names. | <ide><path>ore/src/main/java/de/gurkenlabs/litiengine/Valign.java
<ide> public enum Valign {
<ide> @XmlEnumValue("bottom")
<ide> DOWN(1f),
<del> @XmlEnumValue("center")
<add> @XmlEnumValue("middle")
<ide> MIDDLE(0.5f),
<ide> @XmlEnumValue("top")
<ide> TOP(0f), |
|
Java | apache-2.0 | 77de2efde93a19b275c3b34f457a84894eebd98a | 0 | pmuetschard/gapid,google/gapid,google/agi,google/gapid,pmuetschard/gapid,google/agi,google/gapid,pmuetschard/gapid,pmuetschard/gapid,google/agi,google/gapid,pmuetschard/gapid,google/agi,google/gapid,google/gapid,google/agi,google/agi,google/agi,pmuetschard/gapid,pmuetschard/gapid,google/agi,google/gapid,google/gapid,pmuetschard/gapid | /*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gapid.views;
import static com.google.gapid.util.Arrays.last;
import static com.google.gapid.util.Colors.BLACK;
import static com.google.gapid.util.Colors.DARK_LUMINANCE_THRESHOLD;
import static com.google.gapid.util.Colors.WHITE;
import static com.google.gapid.util.Colors.getLuminance;
import static com.google.gapid.util.Colors.rgb;
import static com.google.gapid.util.Loadable.MessageType.Error;
import static com.google.gapid.util.Loadable.MessageType.Info;
import static com.google.gapid.widgets.Widgets.createComposite;
import static com.google.gapid.widgets.Widgets.createGroup;
import static com.google.gapid.widgets.Widgets.createStandardTabFolder;
import static com.google.gapid.widgets.Widgets.createStandardTabItem;
import static com.google.gapid.widgets.Widgets.createTableViewer;
import static com.google.gapid.widgets.Widgets.createTreeViewer;
import static com.google.gapid.widgets.Widgets.disposeAllChildren;
import static com.google.gapid.widgets.Widgets.packColumns;
import static com.google.gapid.widgets.Widgets.scheduleIfNotDisposed;
import static java.util.logging.Level.FINE;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gapid.lang.glsl.GlslSourceConfiguration;
import com.google.gapid.models.Analytics.View;
import com.google.gapid.models.Capture;
import com.google.gapid.models.CommandStream;
import com.google.gapid.models.CommandStream.CommandIndex;
import com.google.gapid.models.Models;
import com.google.gapid.models.Resources;
import com.google.gapid.proto.core.pod.Pod;
import com.google.gapid.proto.service.Service;
import com.google.gapid.proto.service.Service.ClientAction;
import com.google.gapid.proto.service.api.API;
import com.google.gapid.rpc.Rpc;
import com.google.gapid.rpc.RpcException;
import com.google.gapid.rpc.SingleInFlight;
import com.google.gapid.rpc.UiCallback;
import com.google.gapid.util.Events;
import com.google.gapid.util.Loadable;
import com.google.gapid.util.Messages;
import com.google.gapid.util.ProtoDebugTextFormat;
import com.google.gapid.widgets.LoadablePanel;
import com.google.gapid.widgets.SearchBox;
import com.google.gapid.widgets.Theme;
import com.google.gapid.widgets.Widgets;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TreeItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* View allowing the inspection and editing of the shader resources.
*/
public class ShaderView extends Composite
implements Tab, Capture.Listener, CommandStream.Listener, Resources.Listener {
protected static final Logger LOG = Logger.getLogger(ShaderView.class.getName());
protected final Models models;
private final Widgets widgets;
private final SingleInFlight shaderRpcController = new SingleInFlight();
private final SingleInFlight programRpcController = new SingleInFlight();
private final LoadablePanel<Composite> loading;
private boolean uiBuiltWithPrograms;
public ShaderView(Composite parent, Models models, Widgets widgets) {
super(parent, SWT.NONE);
this.models = models;
this.widgets = widgets;
setLayout(new FillLayout());
loading = LoadablePanel.create(this, widgets,
panel -> createComposite(panel, new FillLayout(SWT.VERTICAL)));
updateUi(true);
models.capture.addListener(this);
models.commands.addListener(this);
models.resources.addListener(this);
addListener(SWT.Dispose, e -> {
models.capture.removeListener(this);
models.commands.removeListener(this);
models.resources.removeListener(this);
});
}
private Control createShaderTab(Composite parent) {
ShaderPanel panel = new ShaderPanel(parent, models, widgets.theme, Type.shader((data, src) -> {
API.Shader shader = (data == null) ? null : (API.Shader)data.resource;
if (shader != null) {
models.analytics.postInteraction(View.Shaders, ClientAction.Edit);
models.resources.updateResource(data.info, API.ResourceData.newBuilder()
.setShader(shader.toBuilder()
.setSource(src))
.build());
}
}));
panel.addListener(SWT.Selection, e -> {
models.analytics.postInteraction(View.Shaders, ClientAction.SelectShader);
getShaderSource((Data)e.data, panel::setSource);
});
return panel;
}
private Control createProgramTab(Composite parent) {
SashForm splitter = new SashForm(parent, SWT.VERTICAL);
ShaderPanel panel = new ShaderPanel(splitter, models, widgets.theme, Type.program());
Composite uniformsGroup = createGroup(splitter, "Uniforms");
UniformsPanel uniforms = new UniformsPanel(uniformsGroup);
splitter.setWeights(models.settings.programUniformsSplitterWeights);
panel.addListener(SWT.Selection, e -> {
models.analytics.postInteraction(View.Shaders, ClientAction.SelectProgram);
getProgramSource((Data)e.data, program ->
scheduleIfNotDisposed(uniforms, () -> uniforms.setUniforms(program)), panel::setSource);
});
splitter.addListener(
SWT.Dispose, e -> models.settings.programUniformsSplitterWeights = splitter.getWeights());
return splitter;
}
private void getShaderSource(Data data, Consumer<ShaderPanel.Source[]> callback) {
shaderRpcController.start().listen(models.resources.loadResource(data.info),
new UiCallback<API.ResourceData, ShaderPanel.Source>(this, LOG) {
@Override
protected ShaderPanel.Source onRpcThread(Rpc.Result<API.ResourceData> result)
throws RpcException, ExecutionException {
API.Shader shader = result.get().getShader();
data.resource = shader;
return ShaderPanel.Source.of(shader);
}
@Override
protected void onUiThread(ShaderPanel.Source result) {
callback.accept(new ShaderPanel.Source[] { result });
}
});
}
private void getProgramSource(
Data data, Consumer<API.Program> onProgramLoaded, Consumer<ShaderPanel.Source[]> callback) {
programRpcController.start().listen(models.resources.loadResource(data.info),
new UiCallback<API.ResourceData, ShaderPanel.Source[]>(this, LOG) {
@Override
protected ShaderPanel.Source[] onRpcThread(Rpc.Result<API.ResourceData> result)
throws RpcException, ExecutionException {
API.Program program = result.get().getProgram();
data.resource = program;
onProgramLoaded.accept(program);
return ShaderPanel.Source.of(program);
}
@Override
protected void onUiThread(ShaderPanel.Source[] result) {
callback.accept(result);
}
});
}
@Override
public Control getControl() {
return this;
}
@Override
public void reinitialize() {
onCaptureLoadingStart(false);
updateUi(false);
updateLoading();
}
@Override
public void onCaptureLoadingStart(boolean maintainState) {
loading.showMessage(Info, Messages.LOADING_CAPTURE);
}
@Override
public void onCaptureLoaded(Loadable.Message error) {
if (error != null) {
loading.showMessage(Error, Messages.CAPTURE_LOAD_FAILURE);
}
}
@Override
public void onCommandsLoaded() {
if (!models.commands.isLoaded()) {
loading.showMessage(Info, Messages.CAPTURE_LOAD_FAILURE);
} else {
updateLoading();
}
}
@Override
public void onCommandsSelected(CommandIndex path) {
updateLoading();
}
@Override
public void onResourcesLoaded() {
if (!models.resources.isLoaded()) {
loading.showMessage(Info, Messages.CAPTURE_LOAD_FAILURE);
} else {
updateUi(false);
updateLoading();
}
}
private void updateLoading() {
if (models.commands.isLoaded() && models.resources.isLoaded()) {
if (models.commands.getSelectedCommands() == null) {
loading.showMessage(Info, Messages.SELECT_COMMAND);
} else {
loading.stopLoading();
}
}
}
private void updateUi(boolean force) {
boolean hasPrograms = true;
if (models.resources.isLoaded()) {
hasPrograms = models.resources.getResources().stream()
.filter(r -> r.getType() == API.ResourceType.ProgramResource)
.findAny()
.isPresent();
} else if (!force) {
return;
}
if (force || hasPrograms != uiBuiltWithPrograms) {
LOG.log(FINE, "(Re-)creating the shader UI, force: {0}, programs: {1}",
new Object[] { force, hasPrograms });
uiBuiltWithPrograms = hasPrograms;
disposeAllChildren(loading.getContents());
if (hasPrograms) {
TabFolder folder = createStandardTabFolder(loading.getContents());
createStandardTabItem(folder, "Shaders", createShaderTab(folder));
createStandardTabItem(folder, "Programs", createProgramTab(folder));
} else {
createShaderTab(loading.getContents());
}
loading.getContents().requestLayout();
}
}
/**
* Panel displaying the source code of a shader or program.
*/
private static class ShaderPanel extends Composite
implements Resources.Listener, CommandStream.Listener {
private final Models models;
private final Theme theme;
protected final Type type;
private final TreeViewer shaderViewer;
private final Composite sourceComposite;
private final Button pushButton;
private final ViewerFilter currentContextFilter;
private ViewerFilter keywordSearchFilter;
private SourceViewer shaderSourceViewer;
private boolean lastUpdateContainedAllShaders = false;
private List<Data> shaders = Collections.emptyList();
public ShaderPanel(Composite parent, Models models, Theme theme, Type type) {
super(parent, SWT.NONE);
this.models = models;
this.theme = theme;
this.type = type;
setLayout(new FillLayout(SWT.HORIZONTAL));
SashForm splitter = new SashForm(this, SWT.HORIZONTAL);
Composite treeViewerContainer= createComposite(splitter, new GridLayout(1, false), SWT.BORDER);
Composite sourcesContainer = createComposite(splitter, new GridLayout(1, false));
if (type.type == API.ResourceType.ShaderResource) {
splitter.setWeights(models.settings.shaderTreeSplitterWeights);
splitter.addListener(
SWT.Dispose, e -> models.settings.shaderTreeSplitterWeights = splitter.getWeights());
} else if (type.type == API.ResourceType.ProgramResource) {
splitter.setWeights(models.settings.programTreeSplitterWeights);
splitter.addListener(
SWT.Dispose, e -> models.settings.programTreeSplitterWeights = splitter.getWeights());
}
SearchBox searchBox = new SearchBox(treeViewerContainer, true, theme);
searchBox.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
searchBox.addListener(Events.Search, e -> updateSearchFilter(e.text, (e.detail & Events.REGEX) != 0));
currentContextFilter = createCurrentContextFilter(models);
MenuItem contextFilterSelector = new MenuItem(searchBox.getNestedMenu(), SWT.CHECK);
contextFilterSelector.setText("Include all contexts");
contextFilterSelector.addListener(SWT.Selection, e -> updateContextFilter(contextFilterSelector.getSelection()));
contextFilterSelector.setSelection(false);
shaderViewer = createShaderSelector(treeViewerContainer);
shaderViewer.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
updateContextFilter(contextFilterSelector.getSelection());
sourceComposite = createComposite(sourcesContainer, new FillLayout(SWT.VERTICAL));
sourceComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
if (type.isEditable()) {
pushButton = Widgets.createButton(sourcesContainer, "Push Changes",
e -> type.updateShader(
(Data)getLastSelection().getData(),
shaderSourceViewer.getDocument().get()));
pushButton.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, false, false));
pushButton.setEnabled(false);
} else {
pushButton = null;
}
models.commands.addListener(this);
models.resources.addListener(this);
addListener(SWT.Dispose, e -> {
models.commands.removeListener(this);
models.resources.removeListener(this);
});
updateShaders();
}
private TreeViewer createShaderSelector(Composite parent) {
TreeViewer treeViewer = createTreeViewer(parent, SWT.FILL);
treeViewer.getTree().setHeaderVisible(false);
treeViewer.setContentProvider(createShaderContentProvider());
treeViewer.setLabelProvider(new LabelProvider());
treeViewer.getControl().addListener(SWT.Selection, e -> updateSelection());
return treeViewer;
}
private static ITreeContentProvider createShaderContentProvider() {
return new ITreeContentProvider() {
@SuppressWarnings("unchecked")
@Override
public Object[] getElements(Object inputElement) {
return ((List<Data>) inputElement).toArray();
}
@Override
public boolean hasChildren(Object element) {
return false;
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public Object[] getChildren(Object element) {
return null;
}
};
}
private static ViewerFilter createSearchFilter(Pattern pattern) {
return new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return !(element instanceof Data) ||
pattern.matcher(((Data)element).toString()).find();
}
};
}
private static ViewerFilter createCurrentContextFilter(Models models) {
return new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return models.contexts.getSelectedContext().matches(((Data)element).info.getContext());
}
};
}
private SourceViewer createSourcePanel(Composite parent, Source source) {
Group group = createGroup(parent, source.label);
SourceViewer viewer =
new SourceViewer(group, null, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
StyledText textWidget = viewer.getTextWidget();
viewer.setEditable(type.isEditable());
textWidget.setFont(theme.monoSpaceFont());
textWidget.setKeyBinding(ST.SELECT_ALL, ST.SELECT_ALL);
viewer.configure(new GlslSourceConfiguration(theme));
viewer.setDocument(GlslSourceConfiguration.createDocument(source.source));
textWidget.addListener(SWT.KeyDown, e -> {
if (isKey(e, SWT.MOD1, 'z')) {
viewer.doOperation(ITextOperationTarget.UNDO);
} else if (isKey(e, SWT.MOD1, 'y') || isKey(e, SWT.MOD1 | SWT.SHIFT, 'z')) {
viewer.doOperation(ITextOperationTarget.REDO);
}
});
return viewer;
}
private static boolean isKey(Event e, int stateMask, int keyCode) {
return (e.stateMask & stateMask) == stateMask && e.keyCode == keyCode;
}
public void clearSource() {
shaderSourceViewer = null;
disposeAllChildren(sourceComposite);
if (pushButton != null) {
pushButton.setEnabled(false);
}
}
public void setSource(Source[] sources) {
clearSource();
SashForm sourceSash = new SashForm(sourceComposite, SWT.VERTICAL);
for (Source source : sources) {
shaderSourceViewer = createSourcePanel(sourceSash, source);
}
sourceSash.requestLayout();
if (sources.length > 0 && pushButton != null) {
pushButton.setEnabled(true);
}
}
@Override
public void onResourcesLoaded() {
lastUpdateContainedAllShaders = false;
updateShaders();
}
@Override
public void onCommandsSelected(CommandIndex path) {
updateShaders();
}
private TreeItem getLastSelection() {
return last(shaderViewer.getTree().getSelection());
}
private void updateShaders() {
if (models.resources.isLoaded() && models.commands.getSelectedCommands() != null) {
Resources.ResourceList resources = models.resources.getResources(type.type);
// If we previously had created the dropdown with all the shaders and didn't skip any
// this time, the dropdown does not need to change.
if (!lastUpdateContainedAllShaders || !resources.complete) {
shaders = new ArrayList<Data>();
if (!resources.isEmpty()) {
resources.stream()
.map(r -> new Data(r.resource))
.forEach(shaders::add);
}
lastUpdateContainedAllShaders = resources.complete;
// Because TreeViewer will dispose old TreeItems after refresh,
// memorize and select with index, rather than object.
TreeItem selection = getLastSelection();
int selectionIndex = -1;
if (selection != null) {
selectionIndex = shaderViewer.getTree().indexOf(selection);
}
shaderViewer.setInput(shaders);
if (selectionIndex >= 0 && selectionIndex < shaderViewer.getTree().getItemCount()) {
selection = shaderViewer.getTree().getItem(selectionIndex);
shaderViewer.getTree().setSelection(selection);
}
} else {
for (Data data : shaders) {
data.resource = null;
}
}
updateSelection();
}
}
private void updateSelection() {
if (shaderViewer.getTree().getSelectionCount() < 1) {
clearSource();
} else {
Event event = new Event();
event.data = getLastSelection().getData();
notifyListeners(SWT.Selection, event);
}
}
private void updateSearchFilter(String text, boolean isRegex) {
// Keyword Filter is dynamic.
// Remove the previous one each time to avoid filter accumulation.
if (keywordSearchFilter != null) {
shaderViewer.removeFilter(keywordSearchFilter);
}
if (!text.isEmpty()) {
Pattern pattern = SearchBox.getPattern(text, isRegex);
keywordSearchFilter = createSearchFilter(pattern);
shaderViewer.addFilter(keywordSearchFilter);
}
}
private void updateContextFilter(boolean hasAllContext) {
if (currentContextFilter != null) {
shaderViewer.removeFilter(currentContextFilter);
}
if (!hasAllContext) {
shaderViewer.addFilter(currentContextFilter);
}
}
public static class Source {
private static final Source EMPTY_PROGRAM = new Source("Program",
"// No shaders attached to this program at this point in the trace.");
private static final String EMPTY_SHADER =
"// No source attached to this shader at this point in the trace.";
public final String label;
public final String source;
public Source(String label, String source) {
this.label = label;
this.source = source;
}
public static Source of(API.Shader shader) {
return new Source(shader.getType() + " Shader",
shader.getSource().isEmpty() ? EMPTY_SHADER : shader.getSource());
}
public static Source[] of(API.Program program) {
if (program.getShadersCount() == 0) {
return new Source[] { EMPTY_PROGRAM };
}
Source[] source = new Source[program.getShadersCount()];
for (int i = 0; i < source.length; i++) {
source[i] = of(program.getShaders(i));
}
return source;
}
}
protected static interface UpdateShader {
public void updateShader(Data data, String newSource);
}
}
/**
* Panel displaying the uniforms of the current shader program.
*/
private static class UniformsPanel extends Composite {
private final TableViewer table;
private final Map<API.Uniform, Image> images = Maps.newIdentityHashMap();
public UniformsPanel(Composite parent) {
super(parent, SWT.NONE);
setLayout(new FillLayout(SWT.VERTICAL));
table = createTableViewer(
this, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
table.setContentProvider(new ArrayContentProvider());
Widgets.<API.Uniform>createTableColumn(table, "Location",
uniform -> String.valueOf(uniform.getUniformLocation()));
Widgets.<API.Uniform>createTableColumn(table, "Name", API.Uniform::getName);
Widgets.<API.Uniform>createTableColumn(table, "Type",
uniform -> String.valueOf(uniform.getType()));
Widgets.<API.Uniform>createTableColumn(table, "Format",
uniform -> String.valueOf(uniform.getFormat()));
Widgets.<API.Uniform>createTableColumn(table, "Value", uniform -> {
Pod.Value value = uniform.getValue().getPod(); // TODO
switch (uniform.getType()) {
case Int32: return String.valueOf(value.getSint32Array().getValList());
case Uint32: return String.valueOf(value.getUint32Array().getValList());
case Bool: return String.valueOf(value.getBoolArray().getValList());
case Float: return String.valueOf(value.getFloat32Array().getValList());
case Double: return String.valueOf(value.getFloat64Array().getValList());
default: return ProtoDebugTextFormat.shortDebugString(value);
}
},this::getImage);
packColumns(table.getTable());
addListener(SWT.Dispose, e -> clearImages());
}
public void setUniforms(API.Program program) {
List<API.Uniform> uniforms = Lists.newArrayList(program.getUniformsList());
Collections.sort(uniforms, (a, b) -> a.getUniformLocation() - b.getUniformLocation());
clearImages();
table.setInput(uniforms);
table.refresh();
packColumns(table.getTable());
table.getTable().requestLayout();
}
private Image getImage(API.Uniform uniform) {
if (!images.containsKey(uniform)) {
Image image = null;
Pod.Value value = uniform.getValue().getPod(); // TODO
switch (uniform.getType()) {
case Float: {
List<Float> values = value.getFloat32Array().getValList();
if ((values.size() == 3 || values.size() == 4) &&
isColorRange(values.get(0)) && isColorRange(values.get(1)) &&
isColorRange(values.get(2))) {
image = createImage(values.get(0), values.get(1), values.get(2));
}
break;
}
case Double: {
List<Double> values = value.getFloat64Array().getValList();
if ((values.size() == 3 || values.size() == 4) &&
isColorRange(values.get(0)) && isColorRange(values.get(1)) &&
isColorRange(values.get(2))) {
image = createImage(values.get(0), values.get(1), values.get(2));
}
break;
}
default:
// Not a color.
}
images.put(uniform, image);
}
return images.get(uniform);
}
private static boolean isColorRange(double v) {
return v >= 0 && v <= 1;
}
private Image createImage(double r, double g, double b) {
ImageData data = new ImageData(12, 12, 1, new PaletteData(
(getLuminance(r, g, b) < DARK_LUMINANCE_THRESHOLD) ? WHITE : BLACK, rgb(r, g, b)), 1,
new byte[] {
0, 0, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31,
127, -31, 127, -31, 0, 0
} /* Square of 1s with a border of 0s (and padding to 2 bytes per row) */);
return new Image(getDisplay(), data);
}
private void clearImages() {
for (Image image : images.values()) {
if (image != null) {
image.dispose();
}
}
images.clear();
}
}
/**
* Distinguishes between shaders and programs.
*/
private static class Type implements ShaderPanel.UpdateShader {
public final API.ResourceType type;
public final ShaderPanel.UpdateShader onSourceEdited;
public Type(API.ResourceType type, ShaderPanel.UpdateShader onSourceEdited) {
this.type = type;
this.onSourceEdited = onSourceEdited;
}
public static Type shader(ShaderPanel.UpdateShader onSourceEdited) {
return new Type(API.ResourceType.ShaderResource, onSourceEdited);
}
public static Type program() {
return new Type(API.ResourceType.ProgramResource, null);
}
@Override
public void updateShader(Data data, String newSource) {
onSourceEdited.updateShader(data, newSource);
}
public boolean isEditable() {
return onSourceEdited != null;
}
}
/**
* Shader or program data.
*/
private static class Data {
public final Service.Resource info;
public Object resource;
public Data(Service.Resource info) {
this.info = info;
}
@Override
public String toString() {
String handle = info.getHandle();
String label = info.getLabel();
String[] handleComponents = handle.split("(<)|(><)|(>)");
String formattedHandle = handle;
if (handleComponents.length == 3) {
formattedHandle = handleComponents[0] + " " + handleComponents[1] + " | Cmd: " + handleComponents[2];
}
return (label.isEmpty()) ? formattedHandle : formattedHandle + " | " + label;
}
}
}
| gapic/src/main/com/google/gapid/views/ShaderView.java | /*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gapid.views;
import static com.google.gapid.util.Arrays.last;
import static com.google.gapid.util.Colors.BLACK;
import static com.google.gapid.util.Colors.DARK_LUMINANCE_THRESHOLD;
import static com.google.gapid.util.Colors.WHITE;
import static com.google.gapid.util.Colors.getLuminance;
import static com.google.gapid.util.Colors.rgb;
import static com.google.gapid.util.Loadable.MessageType.Error;
import static com.google.gapid.util.Loadable.MessageType.Info;
import static com.google.gapid.widgets.Widgets.createComposite;
import static com.google.gapid.widgets.Widgets.createGroup;
import static com.google.gapid.widgets.Widgets.createStandardTabFolder;
import static com.google.gapid.widgets.Widgets.createStandardTabItem;
import static com.google.gapid.widgets.Widgets.createTableViewer;
import static com.google.gapid.widgets.Widgets.createTreeViewer;
import static com.google.gapid.widgets.Widgets.disposeAllChildren;
import static com.google.gapid.widgets.Widgets.packColumns;
import static com.google.gapid.widgets.Widgets.scheduleIfNotDisposed;
import static java.util.logging.Level.FINE;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gapid.lang.glsl.GlslSourceConfiguration;
import com.google.gapid.models.Analytics.View;
import com.google.gapid.models.Capture;
import com.google.gapid.models.CommandStream;
import com.google.gapid.models.CommandStream.CommandIndex;
import com.google.gapid.models.Models;
import com.google.gapid.models.Resources;
import com.google.gapid.proto.core.pod.Pod;
import com.google.gapid.proto.service.Service;
import com.google.gapid.proto.service.Service.ClientAction;
import com.google.gapid.proto.service.api.API;
import com.google.gapid.rpc.Rpc;
import com.google.gapid.rpc.RpcException;
import com.google.gapid.rpc.SingleInFlight;
import com.google.gapid.rpc.UiCallback;
import com.google.gapid.util.Events;
import com.google.gapid.util.Loadable;
import com.google.gapid.util.Messages;
import com.google.gapid.util.ProtoDebugTextFormat;
import com.google.gapid.widgets.LoadablePanel;
import com.google.gapid.widgets.SearchBox;
import com.google.gapid.widgets.Theme;
import com.google.gapid.widgets.Widgets;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TreeItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* View allowing the inspection and editing of the shader resources.
*/
public class ShaderView extends Composite
implements Tab, Capture.Listener, CommandStream.Listener, Resources.Listener {
protected static final Logger LOG = Logger.getLogger(ShaderView.class.getName());
protected final Models models;
private final Widgets widgets;
private final SingleInFlight shaderRpcController = new SingleInFlight();
private final SingleInFlight programRpcController = new SingleInFlight();
private final LoadablePanel<Composite> loading;
private boolean uiBuiltWithPrograms;
public ShaderView(Composite parent, Models models, Widgets widgets) {
super(parent, SWT.NONE);
this.models = models;
this.widgets = widgets;
setLayout(new FillLayout());
loading = LoadablePanel.create(this, widgets,
panel -> createComposite(panel, new FillLayout(SWT.VERTICAL)));
updateUi(true);
models.capture.addListener(this);
models.commands.addListener(this);
models.resources.addListener(this);
addListener(SWT.Dispose, e -> {
models.capture.removeListener(this);
models.commands.removeListener(this);
models.resources.removeListener(this);
});
}
private Control createShaderTab(Composite parent) {
ShaderPanel panel = new ShaderPanel(parent, models, widgets.theme, Type.shader((data, src) -> {
API.Shader shader = (data == null) ? null : (API.Shader)data.resource;
if (shader != null) {
models.analytics.postInteraction(View.Shaders, ClientAction.Edit);
models.resources.updateResource(data.info, API.ResourceData.newBuilder()
.setShader(shader.toBuilder()
.setSource(src))
.build());
}
}));
panel.addListener(SWT.Selection, e -> {
models.analytics.postInteraction(View.Shaders, ClientAction.SelectShader);
getShaderSource((Data)e.data, panel::setSource);
});
return panel;
}
private Control createProgramTab(Composite parent) {
SashForm splitter = new SashForm(parent, SWT.VERTICAL);
ShaderPanel panel = new ShaderPanel(splitter, models, widgets.theme, Type.program());
Composite uniformsGroup = createGroup(splitter, "Uniforms");
UniformsPanel uniforms = new UniformsPanel(uniformsGroup);
splitter.setWeights(models.settings.programUniformsSplitterWeights);
panel.addListener(SWT.Selection, e -> {
models.analytics.postInteraction(View.Shaders, ClientAction.SelectProgram);
getProgramSource((Data)e.data, program ->
scheduleIfNotDisposed(uniforms, () -> uniforms.setUniforms(program)), panel::setSource);
});
splitter.addListener(
SWT.Dispose, e -> models.settings.programUniformsSplitterWeights = splitter.getWeights());
return splitter;
}
private void getShaderSource(Data data, Consumer<ShaderPanel.Source[]> callback) {
shaderRpcController.start().listen(models.resources.loadResource(data.info),
new UiCallback<API.ResourceData, ShaderPanel.Source>(this, LOG) {
@Override
protected ShaderPanel.Source onRpcThread(Rpc.Result<API.ResourceData> result)
throws RpcException, ExecutionException {
API.Shader shader = result.get().getShader();
data.resource = shader;
return ShaderPanel.Source.of(shader);
}
@Override
protected void onUiThread(ShaderPanel.Source result) {
callback.accept(new ShaderPanel.Source[] { result });
}
});
}
private void getProgramSource(
Data data, Consumer<API.Program> onProgramLoaded, Consumer<ShaderPanel.Source[]> callback) {
programRpcController.start().listen(models.resources.loadResource(data.info),
new UiCallback<API.ResourceData, ShaderPanel.Source[]>(this, LOG) {
@Override
protected ShaderPanel.Source[] onRpcThread(Rpc.Result<API.ResourceData> result)
throws RpcException, ExecutionException {
API.Program program = result.get().getProgram();
data.resource = program;
onProgramLoaded.accept(program);
return ShaderPanel.Source.of(program);
}
@Override
protected void onUiThread(ShaderPanel.Source[] result) {
callback.accept(result);
}
});
}
@Override
public Control getControl() {
return this;
}
@Override
public void reinitialize() {
onCaptureLoadingStart(false);
updateUi(false);
updateLoading();
}
@Override
public void onCaptureLoadingStart(boolean maintainState) {
loading.showMessage(Info, Messages.LOADING_CAPTURE);
}
@Override
public void onCaptureLoaded(Loadable.Message error) {
if (error != null) {
loading.showMessage(Error, Messages.CAPTURE_LOAD_FAILURE);
}
}
@Override
public void onCommandsLoaded() {
if (!models.commands.isLoaded()) {
loading.showMessage(Info, Messages.CAPTURE_LOAD_FAILURE);
} else {
updateLoading();
}
}
@Override
public void onCommandsSelected(CommandIndex path) {
updateLoading();
}
@Override
public void onResourcesLoaded() {
if (!models.resources.isLoaded()) {
loading.showMessage(Info, Messages.CAPTURE_LOAD_FAILURE);
} else {
updateUi(false);
updateLoading();
}
}
private void updateLoading() {
if (models.commands.isLoaded() && models.resources.isLoaded()) {
if (models.commands.getSelectedCommands() == null) {
loading.showMessage(Info, Messages.SELECT_COMMAND);
} else {
loading.stopLoading();
}
}
}
private void updateUi(boolean force) {
boolean hasPrograms = true;
if (models.resources.isLoaded()) {
hasPrograms = models.resources.getResources().stream()
.filter(r -> r.getType() == API.ResourceType.ProgramResource)
.findAny()
.isPresent();
} else if (!force) {
return;
}
if (force || hasPrograms != uiBuiltWithPrograms) {
LOG.log(FINE, "(Re-)creating the shader UI, force: {0}, programs: {1}",
new Object[] { force, hasPrograms });
uiBuiltWithPrograms = hasPrograms;
disposeAllChildren(loading.getContents());
if (hasPrograms) {
TabFolder folder = createStandardTabFolder(loading.getContents());
createStandardTabItem(folder, "Shaders", createShaderTab(folder));
createStandardTabItem(folder, "Programs", createProgramTab(folder));
} else {
createShaderTab(loading.getContents());
}
loading.getContents().requestLayout();
}
}
/**
* Panel displaying the source code of a shader or program.
*/
private static class ShaderPanel extends Composite
implements Resources.Listener, CommandStream.Listener {
private final Models models;
private final Theme theme;
protected final Type type;
private final TreeViewer shaderViewer;
private final Composite sourceComposite;
private final Button pushButton;
private final ViewerFilter currentContextFilter;
private ViewerFilter keywordSearchFilter;
private SourceViewer shaderSourceViewer;
private boolean lastUpdateContainedAllShaders = false;
private List<Data> shaders = Collections.emptyList();
public ShaderPanel(Composite parent, Models models, Theme theme, Type type) {
super(parent, SWT.NONE);
this.models = models;
this.theme = theme;
this.type = type;
setLayout(new FillLayout(SWT.HORIZONTAL));
SashForm splitter = new SashForm(this, SWT.HORIZONTAL);
Composite treeViewerContainer= createComposite(splitter, new GridLayout(1, false), SWT.BORDER);
Composite sourcesContainer = createComposite(splitter, new GridLayout(1, false));
if (type.type == API.ResourceType.ShaderResource) {
splitter.setWeights(models.settings.shaderTreeSplitterWeights);
splitter.addListener(
SWT.Dispose, e -> models.settings.shaderTreeSplitterWeights = splitter.getWeights());
} else if (type.type == API.ResourceType.ProgramResource) {
splitter.setWeights(models.settings.programTreeSplitterWeights);
splitter.addListener(
SWT.Dispose, e -> models.settings.programTreeSplitterWeights = splitter.getWeights());
}
SearchBox searchBox = new SearchBox(treeViewerContainer, true, theme);
searchBox.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
searchBox.addListener(Events.Search, e -> updateSearchFilter(e.text, (e.detail & Events.REGEX) != 0));
currentContextFilter = createCurrentContextFilter(models);
MenuItem contextFilterSelector = new MenuItem(searchBox.getNestedMenu(), SWT.CHECK);
contextFilterSelector.setText("Include all contexts");
contextFilterSelector.addListener(SWT.Selection, e -> updateContextFilter(contextFilterSelector.getSelection()));
contextFilterSelector.setSelection(false);
shaderViewer = createShaderSelector(treeViewerContainer);
shaderViewer.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
updateContextFilter(contextFilterSelector.getSelection());
sourceComposite = createComposite(sourcesContainer, new FillLayout(SWT.VERTICAL));
sourceComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
if (type.isEditable()) {
pushButton = Widgets.createButton(sourcesContainer, "Push Changes",
e -> type.updateShader(
(Data)getLastSelection().getData(),
shaderSourceViewer.getDocument().get()));
pushButton.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, false, false));
pushButton.setEnabled(false);
} else {
pushButton = null;
}
models.commands.addListener(this);
models.resources.addListener(this);
addListener(SWT.Dispose, e -> {
models.commands.removeListener(this);
models.resources.removeListener(this);
});
updateShaders();
}
private TreeViewer createShaderSelector(Composite parent) {
TreeViewer treeViewer = createTreeViewer(parent, SWT.FILL);
treeViewer.getTree().setHeaderVisible(false);
treeViewer.setContentProvider(createShaderContentProvider());
treeViewer.setLabelProvider(new LabelProvider());
treeViewer.getControl().addListener(SWT.Selection, e -> updateSelection());
return treeViewer;
}
private static ITreeContentProvider createShaderContentProvider() {
return new ITreeContentProvider() {
@SuppressWarnings("unchecked")
@Override
public Object[] getElements(Object inputElement) {
return ((List<Data>) inputElement).toArray();
}
@Override
public boolean hasChildren(Object element) {
return false;
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public Object[] getChildren(Object element) {
return null;
}
};
}
private static ViewerFilter createSearchFilter(Pattern pattern) {
return new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return !(element instanceof Data) ||
pattern.matcher(((Data)element).toString()).find();
}
};
}
private static ViewerFilter createCurrentContextFilter(Models models) {
return new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return models.contexts.getSelectedContext().matches(((Data)element).info.getContext());
}
};
}
private SourceViewer createSourcePanel(Composite parent, Source source) {
Group group = createGroup(parent, source.label);
SourceViewer viewer =
new SourceViewer(group, null, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
StyledText textWidget = viewer.getTextWidget();
viewer.setEditable(type.isEditable());
textWidget.setFont(theme.monoSpaceFont());
textWidget.setKeyBinding(ST.SELECT_ALL, ST.SELECT_ALL);
viewer.configure(new GlslSourceConfiguration(theme));
viewer.setDocument(GlslSourceConfiguration.createDocument(source.source));
textWidget.addListener(SWT.KeyDown, e -> {
if (isKey(e, SWT.MOD1, 'z')) {
viewer.doOperation(ITextOperationTarget.UNDO);
} else if (isKey(e, SWT.MOD1, 'y') || isKey(e, SWT.MOD1 | SWT.SHIFT, 'z')) {
viewer.doOperation(ITextOperationTarget.REDO);
}
});
return viewer;
}
private static boolean isKey(Event e, int stateMask, int keyCode) {
return (e.stateMask & stateMask) == stateMask && e.keyCode == keyCode;
}
public void clearSource() {
shaderSourceViewer = null;
disposeAllChildren(sourceComposite);
if (pushButton != null) {
pushButton.setEnabled(false);
}
}
public void setSource(Source[] sources) {
clearSource();
SashForm sourceSash = new SashForm(sourceComposite, SWT.VERTICAL);
for (Source source : sources) {
shaderSourceViewer = createSourcePanel(sourceSash, source);
}
sourceSash.requestLayout();
if (sources.length > 0 && pushButton != null) {
pushButton.setEnabled(true);
}
}
@Override
public void onResourcesLoaded() {
lastUpdateContainedAllShaders = false;
updateShaders();
}
@Override
public void onCommandsSelected(CommandIndex path) {
updateShaders();
}
private TreeItem getLastSelection() {
return last(shaderViewer.getTree().getSelection());
}
private void updateShaders() {
if (models.resources.isLoaded() && models.commands.getSelectedCommands() != null) {
Resources.ResourceList resources = models.resources.getResources(type.type);
// If we previously had created the dropdown with all the shaders and didn't skip any
// this time, the dropdown does not need to change.
if (!lastUpdateContainedAllShaders || !resources.complete) {
shaders = new ArrayList<Data>();
if (!resources.isEmpty()) {
resources.stream()
.map(r -> new Data(r.resource))
.forEach(shaders::add);
}
lastUpdateContainedAllShaders = resources.complete;
// Because TreeViewer will dispose old TreeItems after refresh,
// memorize and select with index, rather than object.
TreeItem selection = getLastSelection();
int selectionIndex = -1;
if (selection != null) {
selectionIndex = shaderViewer.getTree().indexOf(selection);
}
shaderViewer.setInput(shaders);
if (selectionIndex >= 0 && selectionIndex < shaderViewer.getTree().getItemCount()) {
selection = shaderViewer.getTree().getItem(selectionIndex);
shaderViewer.getTree().setSelection(selection);
}
} else {
for (Data data : shaders) {
data.resource = null;
}
}
updateSelection();
}
}
private void updateSelection() {
if (shaderViewer.getTree().getSelectionCount() < 1) {
clearSource();
} else {
Event event = new Event();
event.data = getLastSelection().getData();
notifyListeners(SWT.Selection, event);
}
}
private void updateSearchFilter(String text, boolean isRegex) {
// Keyword Filter is dynamic.
// Remove the previous one each time to avoid filter accumulation.
if (keywordSearchFilter != null) {
shaderViewer.removeFilter(keywordSearchFilter);
}
if (!text.isEmpty()) {
Pattern pattern = SearchBox.getPattern(text, isRegex);
keywordSearchFilter = createSearchFilter(pattern);
shaderViewer.addFilter(keywordSearchFilter);
}
}
private void updateContextFilter(boolean hasAllContext) {
if (currentContextFilter != null) {
shaderViewer.removeFilter(currentContextFilter);
}
if (!hasAllContext) {
shaderViewer.addFilter(currentContextFilter);
}
}
public static class Source {
private static final Source EMPTY_PROGRAM = new Source("Program",
"// No shaders attached to this program at this point in the trace.");
private static final String EMPTY_SHADER =
"// No source attached to this shader at this point in the trace.";
public final String label;
public final String source;
public Source(String label, String source) {
this.label = label;
this.source = source;
}
public static Source of(API.Shader shader) {
return new Source(shader.getType() + " Shader",
shader.getSource().isEmpty() ? EMPTY_SHADER : shader.getSource());
}
public static Source[] of(API.Program program) {
if (program.getShadersCount() == 0) {
return new Source[] { EMPTY_PROGRAM };
}
Source[] source = new Source[program.getShadersCount()];
for (int i = 0; i < source.length; i++) {
source[i] = of(program.getShaders(i));
}
return source;
}
}
protected static interface UpdateShader {
public void updateShader(Data data, String newSource);
}
}
/**
* Panel displaying the uniforms of the current shader program.
*/
private static class UniformsPanel extends Composite {
private final TableViewer table;
private final Map<API.Uniform, Image> images = Maps.newIdentityHashMap();
public UniformsPanel(Composite parent) {
super(parent, SWT.NONE);
setLayout(new FillLayout(SWT.VERTICAL));
table = createTableViewer(
this, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
table.setContentProvider(new ArrayContentProvider());
Widgets.<API.Uniform>createTableColumn(table, "Location",
uniform -> String.valueOf(uniform.getUniformLocation()));
Widgets.<API.Uniform>createTableColumn(table, "Name", API.Uniform::getName);
Widgets.<API.Uniform>createTableColumn(table, "Type",
uniform -> String.valueOf(uniform.getType()));
Widgets.<API.Uniform>createTableColumn(table, "Format",
uniform -> String.valueOf(uniform.getFormat()));
Widgets.<API.Uniform>createTableColumn(table, "Value", uniform -> {
Pod.Value value = uniform.getValue().getPod(); // TODO
switch (uniform.getType()) {
case Int32: return String.valueOf(value.getSint32Array().getValList());
case Uint32: return String.valueOf(value.getUint32Array().getValList());
case Bool: return String.valueOf(value.getBoolArray().getValList());
case Float: return String.valueOf(value.getFloat32Array().getValList());
case Double: return String.valueOf(value.getFloat64Array().getValList());
default: return ProtoDebugTextFormat.shortDebugString(value);
}
},this::getImage);
packColumns(table.getTable());
addListener(SWT.Dispose, e -> clearImages());
}
public void setUniforms(API.Program program) {
List<API.Uniform> uniforms = Lists.newArrayList(program.getUniformsList());
Collections.sort(uniforms, (a, b) -> a.getUniformLocation() - b.getUniformLocation());
clearImages();
table.setInput(uniforms);
table.refresh();
packColumns(table.getTable());
table.getTable().requestLayout();
}
private Image getImage(API.Uniform uniform) {
if (!images.containsKey(uniform)) {
Image image = null;
Pod.Value value = uniform.getValue().getPod(); // TODO
switch (uniform.getType()) {
case Float: {
List<Float> values = value.getFloat32Array().getValList();
if ((values.size() == 3 || values.size() == 4) &&
isColorRange(values.get(0)) && isColorRange(values.get(1)) &&
isColorRange(values.get(2))) {
image = createImage(values.get(0), values.get(1), values.get(2));
}
break;
}
case Double: {
List<Double> values = value.getFloat64Array().getValList();
if ((values.size() == 3 || values.size() == 4) &&
isColorRange(values.get(0)) && isColorRange(values.get(1)) &&
isColorRange(values.get(2))) {
image = createImage(values.get(0), values.get(1), values.get(2));
}
break;
}
default:
// Not a color.
}
images.put(uniform, image);
}
return images.get(uniform);
}
private static boolean isColorRange(double v) {
return v >= 0 && v <= 1;
}
private Image createImage(double r, double g, double b) {
ImageData data = new ImageData(12, 12, 1, new PaletteData(
(getLuminance(r, g, b) < DARK_LUMINANCE_THRESHOLD) ? WHITE : BLACK, rgb(r, g, b)), 1,
new byte[] {
0, 0, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31, 127, -31,
127, -31, 127, -31, 0, 0
} /* Square of 1s with a border of 0s (and padding to 2 bytes per row) */);
return new Image(getDisplay(), data);
}
private void clearImages() {
for (Image image : images.values()) {
if (image != null) {
image.dispose();
}
}
images.clear();
}
}
/**
* Distinguishes between shaders and programs.
*/
private static class Type implements ShaderPanel.UpdateShader {
public final API.ResourceType type;
public final String selectMessage;
public final ShaderPanel.UpdateShader onSourceEdited;
public Type(
API.ResourceType type, String selectMessage, ShaderPanel.UpdateShader onSourceEdited) {
this.type = type;
this.selectMessage = selectMessage;
this.onSourceEdited = onSourceEdited;
}
public static Type shader(ShaderPanel.UpdateShader onSourceEdited) {
return new Type(API.ResourceType.ShaderResource, Messages.SELECT_SHADER, onSourceEdited);
}
public static Type program() {
return new Type(API.ResourceType.ProgramResource, Messages.SELECT_PROGRAM, null);
}
@Override
public void updateShader(Data data, String newSource) {
onSourceEdited.updateShader(data, newSource);
}
public boolean isEditable() {
return onSourceEdited != null;
}
}
/**
* Shader or program data.
*/
private static class Data {
public final Service.Resource info;
public Object resource;
public Data(Service.Resource info) {
this.info = info;
}
@Override
public String toString() {
String handle = info.getHandle();
String label = info.getLabel();
String[] handleComponents = handle.split("(<)|(><)|(>)");
String formattedHandle = handle;
if (handleComponents.length == 3) {
formattedHandle = handleComponents[0] + " " + handleComponents[1] + " | Cmd: " + handleComponents[2];
}
return (label.isEmpty()) ? formattedHandle : formattedHandle + " | " + label;
}
}
}
| Remove the no-longer used dropdown selection message.
| gapic/src/main/com/google/gapid/views/ShaderView.java | Remove the no-longer used dropdown selection message. | <ide><path>apic/src/main/com/google/gapid/views/ShaderView.java
<ide> */
<ide> private static class Type implements ShaderPanel.UpdateShader {
<ide> public final API.ResourceType type;
<del> public final String selectMessage;
<ide> public final ShaderPanel.UpdateShader onSourceEdited;
<ide>
<del> public Type(
<del> API.ResourceType type, String selectMessage, ShaderPanel.UpdateShader onSourceEdited) {
<add> public Type(API.ResourceType type, ShaderPanel.UpdateShader onSourceEdited) {
<ide> this.type = type;
<del> this.selectMessage = selectMessage;
<ide> this.onSourceEdited = onSourceEdited;
<ide> }
<ide>
<ide> public static Type shader(ShaderPanel.UpdateShader onSourceEdited) {
<del> return new Type(API.ResourceType.ShaderResource, Messages.SELECT_SHADER, onSourceEdited);
<add> return new Type(API.ResourceType.ShaderResource, onSourceEdited);
<ide> }
<ide>
<ide> public static Type program() {
<del> return new Type(API.ResourceType.ProgramResource, Messages.SELECT_PROGRAM, null);
<add> return new Type(API.ResourceType.ProgramResource, null);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 440407f6180d541cec41deab1ac5125e3852ebd1 | 0 | billy1380/blogwt,billy1380/blogwt,billy1380/blogwt | //
// FormPart.java
// blogwt
//
// Created by William Shakour (billy1380) on 5 Nov 2015.
// Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.client.markdown.plugin.part;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.ResetButton;
import com.google.gwt.user.client.ui.SubmitButton;
import com.google.gwt.user.client.ui.Widget;
import com.willshex.blogwt.client.DefaultEventBus;
import com.willshex.blogwt.client.Resources;
import com.willshex.blogwt.client.controller.FormController;
import com.willshex.blogwt.client.helper.UiHelper;
import com.willshex.blogwt.client.part.form.ListBoxPart;
import com.willshex.blogwt.client.part.form.ReCaptchaPart;
import com.willshex.blogwt.client.part.form.TextAreaPart;
import com.willshex.blogwt.client.part.form.TextBoxPart;
import com.willshex.blogwt.client.wizard.WizardDialog;
import com.willshex.blogwt.shared.api.datatype.Field;
import com.willshex.blogwt.shared.api.datatype.FieldTypeType;
import com.willshex.blogwt.shared.api.datatype.Form;
import com.willshex.blogwt.shared.api.page.call.SubmitFormRequest;
import com.willshex.blogwt.shared.api.page.call.SubmitFormResponse;
import com.willshex.blogwt.shared.api.page.call.event.SubmitFormEventHandler;
import com.willshex.gson.json.service.shared.StatusType;
/**
* @author William Shakour (billy1380)
*
*/
public class FormPart extends Composite implements SubmitFormEventHandler {
private static final String FORM_CLASS_PARAM_KEY = "formclass";
private static final String BODY_PANEL_CLASS_PARAM_KEY = "bodyclass";
private static final String FIELD_PANEL_CLASS_PARAM_KEY = "fieldclass";
private static final String BUTTON_BAR_CLASS_PARAM_KEY = "buttonclass";
private static final String TYPE = "type";
private static final String NAME = "name";
private static final String DEFAULT_VALUE = "defaultValue";
private static final String ALLOWED_VALUES = "allowedValues";
private static final String RECAPTCH_API_KEY = "recaptchaApiKey";
private static class ConfigLine {
public String type;
public String name;
public String defaultValue;
public List<String> allowedValues;
public Map<String, String> parameters;
public void addAllowedValue (String value) {
if (allowedValues == null) {
allowedValues = new ArrayList<String>();
}
allowedValues.add(value);
}
}
private static FormPartUiBinder uiBinder = GWT
.create(FormPartUiBinder.class);
interface FormPartUiBinder extends UiBinder<Widget, FormPart> {}
@UiField ResetButton btnReset;
@UiField SubmitButton btnSubmit;
@UiField FormPanel frmForm;
@UiField HTMLPanel pnlFields;
@UiField HTMLPanel pnlButtons;
@UiField HTMLPanel pnlBody;
private HandlerRegistration registration;
public FormPart () {
initWidget(uiBinder.createAndBindUi(this));
btnSubmit.getElement().setInnerSafeHtml(
WizardDialog.WizardDialogTemplates.INSTANCE.nextButton("Send"));
}
@UiHandler("frmForm")
void onFormSubmit (SubmitEvent se) {
if (isValid()) {
loading();
Form form = new Form();
// add fields to form
final int count = pnlFields.getWidgetCount();
Widget current;
Field field;
for (int i = 0; i < count; i++) {
current = pnlFields.getWidget(i);
field = null;
if (current instanceof TextBoxPart) {
field = new Field().name(
((TextBoxPart) current).elName.getInnerText())
.value(((TextBoxPart) current).txtValue.getValue());
} else if (current instanceof TextAreaPart) {
field = new Field()
.name(((TextAreaPart) current).elName
.getInnerText()).value(
((TextAreaPart) current).txtValue
.getValue());
} else if (current instanceof ListBoxPart) {
field = new Field().name(
((ListBoxPart) current).elName.getInnerText())
.value(((ListBoxPart) current).lbxValue
.getSelectedValue());
}
if (field != null) {
if (form.fields == null) {
form.fields = new ArrayList<Field>();
}
form.fields.add(field);
}
}
FormController.get().submitForm(form);
} else {
showErrors();
}
se.cancel();
}
@UiHandler("btnReset")
void onResetClicked (ClickEvent ce) {
frmForm.reset();
}
private boolean isValid () {
return true;
}
private void showErrors () {
}
/**
* @param line
*/
public void addFieldWithLine (String line) {
if (line.length() > 0) {
ConfigLine config = parseConfigLine(line);
boolean autofocus = pnlFields.getWidgetCount() == 0;
switch (FieldTypeType.fromString(config.type)) {
case FieldTypeTypeText:
TextBoxPart textBox = new TextBoxPart();
textBox.elName.setInnerHTML(config.name);
UiHelper.addPlaceholder(textBox.txtValue, config.name);
textBox.txtValue.setValue(config.defaultValue);
pnlFields.add(textBox);
if (autofocus) {
UiHelper.autoFocus(textBox.txtValue);
}
break;
case FieldTypeTypeLongText:
TextAreaPart longText = new TextAreaPart();
longText.elName.setInnerHTML(config.name);
UiHelper.addPlaceholder(longText.txtValue, config.name);
longText.txtValue.setValue(config.defaultValue);
longText.txtValue.setVisibleLines(4);
pnlFields.add(longText);
if (autofocus) {
UiHelper.autoFocus(longText.txtValue);
}
break;
case FieldTypeTypeSingleOption:
ListBoxPart listBox = new ListBoxPart();
listBox.elName.setInnerHTML(config.name);
UiHelper.addPlaceholder(listBox.lbxValue, config.name);
if (config.allowedValues != null) {
int size = config.allowedValues.size();
String value;
for (int i = 0; i < size; i++) {
value = config.allowedValues.get(i);
listBox.lbxValue.addItem(value, value);
if (value.equals(config.defaultValue)) {
listBox.lbxValue.setSelectedIndex(i);
}
}
}
pnlFields.add(listBox);
if (autofocus) {
UiHelper.autoFocus(listBox.lbxValue);
}
break;
case FieldTypeTypeCaptcha:
ReCaptchaPart recaptch = new ReCaptchaPart();
recaptch.setApiKey(config.parameters.get(RECAPTCH_API_KEY));
pnlFields.add(recaptch);
break;
}
}
}
private ConfigLine parseConfigLine (String line) {
String[] params = line.split("/");
ConfigLine config = new ConfigLine();
String[] splitParam, allowedValues;
Map<String, String> parameters = new HashMap<String, String>();
for (String param : params) {
splitParam = param.split("=");
if (splitParam.length == 2) {
parameters.put(splitParam[0], splitParam[1]);
switch (splitParam[0]) {
case TYPE:
config.type = splitParam[1];
break;
case NAME:
config.name = splitParam[1];
break;
case DEFAULT_VALUE:
config.defaultValue = splitParam[1];
break;
case ALLOWED_VALUES:
allowedValues = splitParam[1].split(",");
for (String value : allowedValues) {
config.addAllowedValue(value);
}
}
}
}
config.parameters = parameters;
return config;
}
/**
* @param params
*/
public void setParams (Map<String, String> params) {
String[] splitParam;
if (params.containsKey(FORM_CLASS_PARAM_KEY)) {
splitParam = params.get(FORM_CLASS_PARAM_KEY).split(";");
for (String token : splitParam) {
this.addStyleName(token);
}
}
if (params.containsKey(BODY_PANEL_CLASS_PARAM_KEY)) {
splitParam = params.get(BODY_PANEL_CLASS_PARAM_KEY).split(";");
for (String token : splitParam) {
pnlBody.addStyleName(token);
}
}
if (params.containsKey(FIELD_PANEL_CLASS_PARAM_KEY)) {
splitParam = params.get(FIELD_PANEL_CLASS_PARAM_KEY).split(";");
for (String token : splitParam) {
pnlFields.addStyleName(token);
}
}
if (params.containsKey(BUTTON_BAR_CLASS_PARAM_KEY)) {
splitParam = params.get(BUTTON_BAR_CLASS_PARAM_KEY).split(";");
for (String token : splitParam) {
pnlButtons.addStyleName(token);
}
}
}
private void loading () {
btnSubmit.getElement().setInnerSafeHtml(
WizardDialog.WizardDialogTemplates.INSTANCE.loadingButton(
"Sending... ", Resources.RES.primaryLoader()
.getSafeUri()));
}
private void ready () {
btnSubmit.getElement().setInnerSafeHtml(
WizardDialog.WizardDialogTemplates.INSTANCE.nextButton("Send"));
}
/* (non-Javadoc)
*
* @see
* com.willshex.blogwt.shared.api.page.call.event.SubmitFormEventHandler
* #submitFormSuccess
* (com.willshex.blogwt.shared.api.page.call.SubmitFormRequest,
* com.willshex.blogwt.shared.api.page.call.SubmitFormResponse) */
@Override
public void submitFormSuccess (SubmitFormRequest input,
SubmitFormResponse output) {
if (output.status == StatusType.StatusTypeSuccess) {
// show submission success message
reset();
}
ready();
}
/* (non-Javadoc)
*
* @see
* com.willshex.blogwt.shared.api.page.call.event.SubmitFormEventHandler
* #submitFormFailure
* (com.willshex.blogwt.shared.api.page.call.SubmitFormRequest,
* java.lang.Throwable) */
@Override
public void submitFormFailure (SubmitFormRequest input, Throwable caught) {
ready();
}
private void reset () {
frmForm.reset();
}
/* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.Composite#onAttach() */
@Override
protected void onAttach () {
super.onAttach();
registration = DefaultEventBus.get().addHandlerToSource(
SubmitFormEventHandler.TYPE, FormController.get(), this);
}
/* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.Composite#onDetach() */
@Override
protected void onDetach () {
super.onDetach();
if (registration != null) {
registration.removeHandler();
}
}
}
| src/main/java/com/willshex/blogwt/client/markdown/plugin/part/FormPart.java | //
// FormPart.java
// blogwt
//
// Created by William Shakour (billy1380) on 5 Nov 2015.
// Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.client.markdown.plugin.part;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.ResetButton;
import com.google.gwt.user.client.ui.SubmitButton;
import com.google.gwt.user.client.ui.Widget;
import com.willshex.blogwt.client.DefaultEventBus;
import com.willshex.blogwt.client.Resources;
import com.willshex.blogwt.client.controller.FormController;
import com.willshex.blogwt.client.helper.UiHelper;
import com.willshex.blogwt.client.part.form.ListBoxPart;
import com.willshex.blogwt.client.part.form.ReCaptchaPart;
import com.willshex.blogwt.client.part.form.TextAreaPart;
import com.willshex.blogwt.client.part.form.TextBoxPart;
import com.willshex.blogwt.client.wizard.WizardDialog;
import com.willshex.blogwt.shared.api.datatype.Field;
import com.willshex.blogwt.shared.api.datatype.Form;
import com.willshex.blogwt.shared.api.page.call.SubmitFormRequest;
import com.willshex.blogwt.shared.api.page.call.SubmitFormResponse;
import com.willshex.blogwt.shared.api.page.call.event.SubmitFormEventHandler;
import com.willshex.gson.json.service.shared.StatusType;
/**
* @author William Shakour (billy1380)
*
*/
public class FormPart extends Composite implements SubmitFormEventHandler {
private static final String FORM_CLASS_PARAM_KEY = "formclass";
private static final String BODY_PANEL_CLASS_PARAM_KEY = "bodyclass";
private static final String FIELD_PANEL_CLASS_PARAM_KEY = "fieldclass";
private static final String BUTTON_BAR_CLASS_PARAM_KEY = "buttonclass";
private static final String TYPE = "type";
private static final String NAME = "name";
private static final String DEFAULT_VALUE = "defaultValue";
private static final String ALLOWED_VALUES = "allowedValues";
private static final String RECAPTCH_API_KEY = "recaptchaApiKey";
private static final String TEXT_TYPE = "text";
private static final String ONE_OPTION_TYPE = "oneOption";
private static final String LONG_TEXT_TYPE = "longText";
private static final String CAPTCHA_TYPE = "captcha";
private static class ConfigLine {
public String type;
public String name;
public String defaultValue;
public List<String> allowedValues;
public Map<String, String> parameters;
public void addAllowedValue (String value) {
if (allowedValues == null) {
allowedValues = new ArrayList<String>();
}
allowedValues.add(value);
}
}
private static FormPartUiBinder uiBinder = GWT
.create(FormPartUiBinder.class);
interface FormPartUiBinder extends UiBinder<Widget, FormPart> {}
@UiField ResetButton btnReset;
@UiField SubmitButton btnSubmit;
@UiField FormPanel frmForm;
@UiField HTMLPanel pnlFields;
@UiField HTMLPanel pnlButtons;
@UiField HTMLPanel pnlBody;
private HandlerRegistration registration;
public FormPart () {
initWidget(uiBinder.createAndBindUi(this));
btnSubmit.getElement().setInnerSafeHtml(
WizardDialog.WizardDialogTemplates.INSTANCE.nextButton("Send"));
}
@UiHandler("frmForm")
void onFormSubmit (SubmitEvent se) {
if (isValid()) {
loading();
Form form = new Form();
// add fields to form
final int count = pnlFields.getWidgetCount();
Widget current;
Field field;
for (int i = 0; i < count; i++) {
current = pnlFields.getWidget(i);
field = null;
if (current instanceof TextBoxPart) {
field = new Field().name(
((TextBoxPart) current).elName.getInnerText())
.value(((TextBoxPart) current).txtValue.getValue());
} else if (current instanceof TextAreaPart) {
field = new Field()
.name(((TextAreaPart) current).elName
.getInnerText()).value(
((TextAreaPart) current).txtValue
.getValue());
} else if (current instanceof ListBoxPart) {
field = new Field().name(
((ListBoxPart) current).elName.getInnerText())
.value(((ListBoxPart) current).lbxValue
.getSelectedValue());
}
if (field != null) {
if (form.fields == null) {
form.fields = new ArrayList<Field>();
}
form.fields.add(field);
}
}
FormController.get().submitForm(form);
} else {
showErrors();
}
se.cancel();
}
@UiHandler("btnReset")
void onResetClicked (ClickEvent ce) {
frmForm.reset();
}
private boolean isValid () {
return true;
}
private void showErrors () {
}
/**
* @param line
*/
public void addFieldWithLine (String line) {
if (line.length() > 0) {
ConfigLine config = parseConfigLine(line);
boolean autofocus = pnlFields.getWidgetCount() == 0;
switch (config.type) {
case TEXT_TYPE:
TextBoxPart textBox = new TextBoxPart();
textBox.elName.setInnerHTML(config.name);
UiHelper.addPlaceholder(textBox.txtValue, config.name);
textBox.txtValue.setValue(config.defaultValue);
pnlFields.add(textBox);
if (autofocus) {
UiHelper.autoFocus(textBox.txtValue);
}
break;
case LONG_TEXT_TYPE:
TextAreaPart longText = new TextAreaPart();
longText.elName.setInnerHTML(config.name);
UiHelper.addPlaceholder(longText.txtValue, config.name);
longText.txtValue.setValue(config.defaultValue);
longText.txtValue.setVisibleLines(4);
pnlFields.add(longText);
if (autofocus) {
UiHelper.autoFocus(longText.txtValue);
}
break;
case ONE_OPTION_TYPE:
ListBoxPart listBox = new ListBoxPart();
listBox.elName.setInnerHTML(config.name);
UiHelper.addPlaceholder(listBox.lbxValue, config.name);
if (config.allowedValues != null) {
int size = config.allowedValues.size();
String value;
for (int i = 0; i < size; i++) {
value = config.allowedValues.get(i);
listBox.lbxValue.addItem(value, value);
if (value.equals(config.defaultValue)) {
listBox.lbxValue.setSelectedIndex(i);
}
}
}
pnlFields.add(listBox);
if (autofocus) {
UiHelper.autoFocus(listBox.lbxValue);
}
break;
case CAPTCHA_TYPE:
ReCaptchaPart recaptch = new ReCaptchaPart();
recaptch.setApiKey(config.parameters.get(RECAPTCH_API_KEY));
pnlFields.add(recaptch);
break;
}
}
}
private ConfigLine parseConfigLine (String line) {
String[] params = line.split("/");
ConfigLine config = new ConfigLine();
String[] splitParam, allowedValues;
Map<String, String> parameters = new HashMap<String, String>();
for (String param : params) {
splitParam = param.split("=");
if (splitParam.length == 2) {
parameters.put(splitParam[0], splitParam[1]);
switch (splitParam[0]) {
case TYPE:
config.type = splitParam[1];
break;
case NAME:
config.name = splitParam[1];
break;
case DEFAULT_VALUE:
config.defaultValue = splitParam[1];
break;
case ALLOWED_VALUES:
allowedValues = splitParam[1].split(",");
for (String value : allowedValues) {
config.addAllowedValue(value);
}
}
}
}
config.parameters = parameters;
return config;
}
/**
* @param params
*/
public void setParams (Map<String, String> params) {
String[] splitParam;
if (params.containsKey(FORM_CLASS_PARAM_KEY)) {
splitParam = params.get(FORM_CLASS_PARAM_KEY).split(";");
for (String token : splitParam) {
this.addStyleName(token);
}
}
if (params.containsKey(BODY_PANEL_CLASS_PARAM_KEY)) {
splitParam = params.get(BODY_PANEL_CLASS_PARAM_KEY).split(";");
for (String token : splitParam) {
pnlBody.addStyleName(token);
}
}
if (params.containsKey(FIELD_PANEL_CLASS_PARAM_KEY)) {
splitParam = params.get(FIELD_PANEL_CLASS_PARAM_KEY).split(";");
for (String token : splitParam) {
pnlFields.addStyleName(token);
}
}
if (params.containsKey(BUTTON_BAR_CLASS_PARAM_KEY)) {
splitParam = params.get(BUTTON_BAR_CLASS_PARAM_KEY).split(";");
for (String token : splitParam) {
pnlButtons.addStyleName(token);
}
}
}
private void loading () {
btnSubmit.getElement().setInnerSafeHtml(
WizardDialog.WizardDialogTemplates.INSTANCE.loadingButton(
"Sending... ", Resources.RES.primaryLoader()
.getSafeUri()));
}
private void ready () {
btnSubmit.getElement().setInnerSafeHtml(
WizardDialog.WizardDialogTemplates.INSTANCE.nextButton("Send"));
}
/* (non-Javadoc)
*
* @see
* com.willshex.blogwt.shared.api.page.call.event.SubmitFormEventHandler
* #submitFormSuccess
* (com.willshex.blogwt.shared.api.page.call.SubmitFormRequest,
* com.willshex.blogwt.shared.api.page.call.SubmitFormResponse) */
@Override
public void submitFormSuccess (SubmitFormRequest input,
SubmitFormResponse output) {
if (output.status == StatusType.StatusTypeSuccess) {
// show submission success message
reset();
}
ready();
}
/* (non-Javadoc)
*
* @see
* com.willshex.blogwt.shared.api.page.call.event.SubmitFormEventHandler
* #submitFormFailure
* (com.willshex.blogwt.shared.api.page.call.SubmitFormRequest,
* java.lang.Throwable) */
@Override
public void submitFormFailure (SubmitFormRequest input, Throwable caught) {
ready();
}
private void reset () {
frmForm.reset();
}
/* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.Composite#onAttach() */
@Override
protected void onAttach () {
super.onAttach();
registration = DefaultEventBus.get().addHandlerToSource(
SubmitFormEventHandler.TYPE, FormController.get(), this);
}
/* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.Composite#onDetach() */
@Override
protected void onDetach () {
super.onDetach();
if (registration != null) {
registration.removeHandler();
}
}
}
| using field types instead of constants | src/main/java/com/willshex/blogwt/client/markdown/plugin/part/FormPart.java | using field types instead of constants | <ide><path>rc/main/java/com/willshex/blogwt/client/markdown/plugin/part/FormPart.java
<ide> import com.willshex.blogwt.client.part.form.TextBoxPart;
<ide> import com.willshex.blogwt.client.wizard.WizardDialog;
<ide> import com.willshex.blogwt.shared.api.datatype.Field;
<add>import com.willshex.blogwt.shared.api.datatype.FieldTypeType;
<ide> import com.willshex.blogwt.shared.api.datatype.Form;
<ide> import com.willshex.blogwt.shared.api.page.call.SubmitFormRequest;
<ide> import com.willshex.blogwt.shared.api.page.call.SubmitFormResponse;
<ide> private static final String ALLOWED_VALUES = "allowedValues";
<ide>
<ide> private static final String RECAPTCH_API_KEY = "recaptchaApiKey";
<del>
<del> private static final String TEXT_TYPE = "text";
<del> private static final String ONE_OPTION_TYPE = "oneOption";
<del> private static final String LONG_TEXT_TYPE = "longText";
<del> private static final String CAPTCHA_TYPE = "captcha";
<ide>
<ide> private static class ConfigLine {
<ide> public String type;
<ide>
<ide> boolean autofocus = pnlFields.getWidgetCount() == 0;
<ide>
<del> switch (config.type) {
<del> case TEXT_TYPE:
<add> switch (FieldTypeType.fromString(config.type)) {
<add> case FieldTypeTypeText:
<ide> TextBoxPart textBox = new TextBoxPart();
<ide> textBox.elName.setInnerHTML(config.name);
<ide> UiHelper.addPlaceholder(textBox.txtValue, config.name);
<ide> UiHelper.autoFocus(textBox.txtValue);
<ide> }
<ide> break;
<del> case LONG_TEXT_TYPE:
<add> case FieldTypeTypeLongText:
<ide> TextAreaPart longText = new TextAreaPart();
<ide> longText.elName.setInnerHTML(config.name);
<ide> UiHelper.addPlaceholder(longText.txtValue, config.name);
<ide> UiHelper.autoFocus(longText.txtValue);
<ide> }
<ide> break;
<del> case ONE_OPTION_TYPE:
<add> case FieldTypeTypeSingleOption:
<ide> ListBoxPart listBox = new ListBoxPart();
<ide> listBox.elName.setInnerHTML(config.name);
<ide> UiHelper.addPlaceholder(listBox.lbxValue, config.name);
<ide> UiHelper.autoFocus(listBox.lbxValue);
<ide> }
<ide> break;
<del> case CAPTCHA_TYPE:
<add> case FieldTypeTypeCaptcha:
<ide> ReCaptchaPart recaptch = new ReCaptchaPart();
<ide> recaptch.setApiKey(config.parameters.get(RECAPTCH_API_KEY));
<ide> pnlFields.add(recaptch); |
|
Java | mit | 51d9efb0bc84e67bbe62a050686ff75291fe77ac | 0 | karlmdavis/ksoap2-android | /* Copyright (c) 2003,2004 Stefan Haustein, Oberhausen, Rhld., Germany
* Copyright (c) 2006, James Seigel, Calgary, AB., Canada
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE. */
package org.ksoap2.serialization;
import java.io.*;
import org.xmlpull.v1.*;
public class MarshalFloat implements Marshal {
public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo propertyInfo) throws IOException, XmlPullParserException {
String stringValue = parser.nextText();
Object result;
if (name.equals("float"))
result = new Float(stringValue);
else if (name.equals("double"))
result = new Double(stringValue);
else if (name.equals("decimal"))
result = new java.math.BigDecimal(stringValue);
else
throw new RuntimeException("float, double, or decimal expected");
return result;
}
public void writeInstance(XmlSerializer writer, Object instance) throws IOException {
writer.text(instance.toString());
}
public void register(SoapSerializationEnvelope cm) {
cm.addMapping(cm.xsd, "float", Float.class, this);
cm.addMapping(cm.xsd, "double", Double.class, this);
cm.addMapping(cm.xsd, "decimal", java.math.BigDecimal.class, this);
}
}
| ksoap2/ksoap2/src_j2se/org/ksoap2/serialization/MarshalFloat.java | /* Copyright (c) 2003,2004,2006 Stefan Haustein, Oberhausen, Rhld., Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE. */
package org.ksoap2.serialization;
import java.io.*;
import org.xmlpull.v1.*;
public class MarshalFloat implements Marshal {
public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo propertyInfo) throws IOException, XmlPullParserException {
String stringValue = parser.nextText();
Object result;
if (name.equals("float"))
result = new Float(stringValue);
else if (name.equals("double"))
result = new Double(stringValue);
else if (name.equals("decimal"))
result = new java.math.BigDecimal(stringValue);
else
throw new RuntimeException("float, double, or decimal expected");
return result;
}
public void writeInstance(XmlSerializer writer, Object instance) throws IOException {
writer.text(instance.toString());
}
public void register(SoapSerializationEnvelope cm) {
cm.addMapping(cm.xsd, "float", Float.class, this);
cm.addMapping(cm.xsd, "double", Double.class, this);
cm.addMapping(cm.xsd, "decimal", java.math.BigDecimal.class, this);
}
}
| Added license information to marshal float
git-svn-id: 58e116579136dd0783a3c5e6645177e33acc8aa3@74 dcb2794c-2714-0410-ae40-8be703bc5849
| ksoap2/ksoap2/src_j2se/org/ksoap2/serialization/MarshalFloat.java | Added license information to marshal float | <ide><path>soap2/ksoap2/src_j2se/org/ksoap2/serialization/MarshalFloat.java
<del>/* Copyright (c) 2003,2004,2006 Stefan Haustein, Oberhausen, Rhld., Germany
<del> *
<add>/* Copyright (c) 2003,2004 Stefan Haustein, Oberhausen, Rhld., Germany
<add> * Copyright (c) 2006, James Seigel, Calgary, AB., Canada
<add> *
<ide> * Permission is hereby granted, free of charge, to any person obtaining a copy
<ide> * of this software and associated documentation files (the "Software"), to deal
<ide> * in the Software without restriction, including without limitation the rights |
|
Java | apache-2.0 | 15010058dfb4666434477c14a733f1b2ebc4728d | 0 | vlsidlyarevich/unity,vlsidlyarevich/unity,vlsidlyarevich/unity,vlsidlyarevich/unity | package com.github.vlsidlyarevich.unity.web.controller;
import com.github.vlsidlyarevich.unity.db.service.StorageService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
//@RunWith(SpringRunner.class)
//@SpringBootTest
public class ImageControllerTest {
// @Autowired
private WebApplicationContext context;
// @Autowired
private StorageService storageService;
private MockMvc mvc;
// @After
public void after() throws Exception {
storageService.deleteAll();
}
// @Before
public void setupMvc() throws Exception {
storageService.deleteAll();
this.mvc = webAppContextSetup(context).build();
}
// @Test
public void uploadImageTest() throws Exception {
MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
mvc.perform(MockMvcRequestBuilders.fileUpload("/api/v1/images/upload")
.file(image)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(MockMvcResultMatchers.status().isCreated());
}
// @Test
public void getImageByIdTest() throws Exception {
MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
String imageId = storageService.store(image);
mvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, "/api/v1/images/" + imageId)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().bytes(image.getBytes()));
}
// @Test
public void deleteImageTest() throws Exception {
MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
String imageId = storageService.store(image);
mvc.perform(MockMvcRequestBuilders.request(HttpMethod.DELETE, "/api/v1/images/" + imageId)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
| src/test/java/com/github/vlsidlyarevich/unity/web/controller/ImageControllerTest.java | package com.github.vlsidlyarevich.unity.web.controller;
import com.github.vlsidlyarevich.unity.db.service.StorageService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ImageControllerTest {
@Autowired
private WebApplicationContext context;
@Autowired
private StorageService storageService;
private MockMvc mvc;
@After
public void after() throws Exception {
storageService.deleteAll();
}
@Before
public void setupMvc() throws Exception {
storageService.deleteAll();
this.mvc = webAppContextSetup(context).build();
}
@Test
public void uploadImageTest() throws Exception {
MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
mvc.perform(MockMvcRequestBuilders.fileUpload("/api/v1/images/upload")
.file(image)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(MockMvcResultMatchers.status().isCreated());
}
@Test
public void getImageByIdTest() throws Exception {
MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
String imageId = storageService.store(image);
mvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, "/api/v1/images/" + imageId)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().bytes(image.getBytes()));
}
@Test
public void deleteImageTest() throws Exception {
MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
String imageId = storageService.store(image);
mvc.perform(MockMvcRequestBuilders.request(HttpMethod.DELETE, "/api/v1/images/" + imageId)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
| Backend: temporarily commented ImageControllerTest
| src/test/java/com/github/vlsidlyarevich/unity/web/controller/ImageControllerTest.java | Backend: temporarily commented ImageControllerTest | <ide><path>rc/test/java/com/github/vlsidlyarevich/unity/web/controller/ImageControllerTest.java
<ide>
<ide> import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
<ide>
<del>@RunWith(SpringRunner.class)
<del>@SpringBootTest
<add>//@RunWith(SpringRunner.class)
<add>//@SpringBootTest
<ide> public class ImageControllerTest {
<ide>
<del> @Autowired
<add>// @Autowired
<ide> private WebApplicationContext context;
<ide>
<del> @Autowired
<add>// @Autowired
<ide> private StorageService storageService;
<ide>
<ide> private MockMvc mvc;
<ide>
<del> @After
<add>// @After
<ide> public void after() throws Exception {
<ide> storageService.deleteAll();
<ide> }
<ide>
<del> @Before
<add>// @Before
<ide> public void setupMvc() throws Exception {
<ide> storageService.deleteAll();
<ide> this.mvc = webAppContextSetup(context).build();
<ide> }
<ide>
<del> @Test
<add>// @Test
<ide> public void uploadImageTest() throws Exception {
<ide> MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
<ide>
<ide> .andExpect(MockMvcResultMatchers.status().isCreated());
<ide> }
<ide>
<del> @Test
<add>// @Test
<ide> public void getImageByIdTest() throws Exception {
<ide> MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
<ide> String imageId = storageService.store(image);
<ide> .andExpect(MockMvcResultMatchers.content().bytes(image.getBytes()));
<ide> }
<ide>
<del> @Test
<add>// @Test
<ide> public void deleteImageTest() throws Exception {
<ide> MockMultipartFile image = new MockMultipartFile("file", "Image.png", null, "content".getBytes());
<ide> String imageId = storageService.store(image); |
|
Java | apache-2.0 | d8b00e6df840d5e72b478d26baa094f67a6c32e7 | 0 | nethad/clustermeister,nethad/clustermeister | /*
* Copyright 2012 The Clustermeister Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.nethad.clustermeister.provisioning.torque;
import com.github.nethad.clustermeister.api.Node;
import com.github.nethad.clustermeister.api.NodeConfiguration;
import com.github.nethad.clustermeister.api.NodeType;
import com.github.nethad.clustermeister.provisioning.jppf.JPPFDriverConfigurationSource;
import com.google.common.util.concurrent.ListenableFuture;
/**
*
* @author thomas
*/
public class TorqueJPPFTestSetup {
private static final int NUMBER_OF_NODES = 6;
public static void main(String... args) {
new TorqueJPPFTestSetup().execute();
}
private TorqueNodeManager torqueNodeManager;
private void execute() {
System.setProperty("jppf.config.plugin", JPPFDriverConfigurationSource.class.getCanonicalName());
torqueNodeManager = new TorqueNodeManager(null);
startDriver();
startNodes();
}
private void startDriver() {
// JPPFDriver.main("noLauncher");
// ProcessLauncher processLauncher = new ProcessLauncher("org.jppf.server.JPPFDriver");
// processLauncher.run();
// TorqueLocalRunner runner = new TorqueLocalRunner();
// runner.start();
NodeConfiguration nodeConfiguration = new TorqueNodeConfiguration(NodeType.DRIVER);
ListenableFuture<? extends Node> node = torqueNodeManager.addNode(nodeConfiguration);
System.out.println("driver = " + node);
// try {
// Thread.sleep(5000);
// System.out.println("runner.stopDriver()");
// runner.stopDriver();
// } catch (InterruptedException ex) {
// Logger.getLogger(TorqueJPPFTestSetup.class.getName()).log(Level.SEVERE, null, ex);
// }
}
private void startNodes() {
torqueNodeManager.deployResources();
NodeConfiguration nodeConfiguration = new TorqueNodeConfiguration(NodeType.NODE);
for (int i = 0; i<NUMBER_OF_NODES; i++) {
torqueNodeManager.addNode(nodeConfiguration);
}
}
private class TorqueLocalRunner extends Thread {
private TorqueJPPFDriverDeployer deployer;
@Override
public void run() {
System.out.println("Start driver");
deployer = new TorqueJPPFDriverDeployer();
deployer.execute();
}
public void stopDriver() {
deployer.stopLocalDriver();
}
}
}
| provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/torque/TorqueJPPFTestSetup.java | /*
* Copyright 2012 The Clustermeister Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.nethad.clustermeister.provisioning.torque;
import com.github.nethad.clustermeister.api.NodeConfiguration;
import com.github.nethad.clustermeister.api.NodeType;
import com.github.nethad.clustermeister.provisioning.jppf.JPPFDriverConfigurationSource;
/**
*
* @author thomas
*/
public class TorqueJPPFTestSetup {
private static final int NUMBER_OF_NODES = 6;
public static void main(String... args) {
new TorqueJPPFTestSetup().execute();
}
private void execute() {
System.setProperty("jppf.config.plugin", JPPFDriverConfigurationSource.class.getCanonicalName());
startDriver();
startNodes();
}
private void startDriver() {
// JPPFDriver.main("noLauncher");
// ProcessLauncher processLauncher = new ProcessLauncher("org.jppf.server.JPPFDriver");
// processLauncher.run();
TorqueLocalRunner runner = new TorqueLocalRunner();
runner.start();
// try {
// Thread.sleep(5000);
// System.out.println("runner.stopDriver()");
// runner.stopDriver();
// } catch (InterruptedException ex) {
// Logger.getLogger(TorqueJPPFTestSetup.class.getName()).log(Level.SEVERE, null, ex);
// }
}
private void startNodes() {
// System.out.println("Start "+NUMBER_OF_NODES+" nodes.");
// new TorqueJPPFNodeDeployer().execute(NUMBER_OF_NODES);
TorqueNodeManager torqueNodeManager = new TorqueNodeManager(null);
torqueNodeManager.deployResources();
NodeConfiguration nodeConfiguration = new TorqueNodeConfiguration(NodeType.NODE);
for (int i = 0; i<NUMBER_OF_NODES; i++) {
torqueNodeManager.addNode(nodeConfiguration);
}
}
private class TorqueLocalRunner extends Thread {
private TorqueJPPFDriverDeployer deployer;
@Override
public void run() {
System.out.println("Start driver");
deployer = new TorqueJPPFDriverDeployer();
deployer.execute();
}
public void stopDriver() {
deployer.stopLocalDriver();
}
}
}
| use TorqueNodeManager to start driver
| provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/torque/TorqueJPPFTestSetup.java | use TorqueNodeManager to start driver | <ide><path>rovisioning/src/main/java/com/github/nethad/clustermeister/provisioning/torque/TorqueJPPFTestSetup.java
<ide> */
<ide> package com.github.nethad.clustermeister.provisioning.torque;
<ide>
<add>import com.github.nethad.clustermeister.api.Node;
<ide> import com.github.nethad.clustermeister.api.NodeConfiguration;
<ide> import com.github.nethad.clustermeister.api.NodeType;
<ide> import com.github.nethad.clustermeister.provisioning.jppf.JPPFDriverConfigurationSource;
<add>import com.google.common.util.concurrent.ListenableFuture;
<ide>
<ide> /**
<ide> *
<ide> public static void main(String... args) {
<ide> new TorqueJPPFTestSetup().execute();
<ide> }
<add> private TorqueNodeManager torqueNodeManager;
<ide>
<ide> private void execute() {
<ide> System.setProperty("jppf.config.plugin", JPPFDriverConfigurationSource.class.getCanonicalName());
<add> torqueNodeManager = new TorqueNodeManager(null);
<ide>
<ide> startDriver();
<ide> startNodes();
<ide> // ProcessLauncher processLauncher = new ProcessLauncher("org.jppf.server.JPPFDriver");
<ide> // processLauncher.run();
<ide>
<del> TorqueLocalRunner runner = new TorqueLocalRunner();
<del> runner.start();
<del>
<del>// try {
<del>// Thread.sleep(5000);
<del>// System.out.println("runner.stopDriver()");
<del>// runner.stopDriver();
<del>// } catch (InterruptedException ex) {
<del>// Logger.getLogger(TorqueJPPFTestSetup.class.getName()).log(Level.SEVERE, null, ex);
<del>// }
<add>// TorqueLocalRunner runner = new TorqueLocalRunner();
<add>// runner.start();
<add> NodeConfiguration nodeConfiguration = new TorqueNodeConfiguration(NodeType.DRIVER);
<add> ListenableFuture<? extends Node> node = torqueNodeManager.addNode(nodeConfiguration);
<add> System.out.println("driver = " + node);
<add> // try {
<add> // Thread.sleep(5000);
<add> // System.out.println("runner.stopDriver()");
<add> // runner.stopDriver();
<add> // } catch (InterruptedException ex) {
<add> // Logger.getLogger(TorqueJPPFTestSetup.class.getName()).log(Level.SEVERE, null, ex);
<add> // }
<ide> }
<ide>
<ide> private void startNodes() {
<del> // System.out.println("Start "+NUMBER_OF_NODES+" nodes.");
<del> // new TorqueJPPFNodeDeployer().execute(NUMBER_OF_NODES);
<del> TorqueNodeManager torqueNodeManager = new TorqueNodeManager(null);
<add>
<ide> torqueNodeManager.deployResources();
<ide> NodeConfiguration nodeConfiguration = new TorqueNodeConfiguration(NodeType.NODE);
<ide> for (int i = 0; i<NUMBER_OF_NODES; i++) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.